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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IBeacon.sol"; /// @title BeaconProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract that uses the beacon pattern for instant upgrades contract BeaconProxy { address private immutable BEACON; constructor(bytes memory _constructData, address _beacon) public { BEACON = _beacon; (bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall( _constructData ); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = IBeacon(BEACON).getCanonicalLib(); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } receive() external payable {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); }
@title IBeacon interface @author Enzyme Council <[email protected]>
interface IBeacon { function getCanonicalLib() external view returns (address); This file is part of the Enzyme Protocol. }
5,891,685
[ 1, 45, 1919, 16329, 1560, 225, 1374, 94, 2942, 73, 385, 465, 71, 330, 411, 63, 3652, 131, 259, 1117, 65, 34, 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, 5831, 467, 1919, 16329, 288, 203, 565, 445, 13350, 5664, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 1220, 585, 353, 1087, 434, 326, 1374, 94, 2942, 73, 4547, 18, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 <0.7.0; contract Secuid{ struct Identity { /* * @Identity: hold identity data and hash * @Hash: a bytes32 keccak256 hash of data string. Used for check the validity of data. * @Checker is checker address verified this identity * @Data: a json string encrypted (json --- encrypt --> @Data --- decrypt --> json) */ bytes32 Hash; address Checker; string Data; } struct Wallet { /* * @Wallet hold public data of an address * @Owner is owner address if this wallet * @Data is public data of this wallet */ address Owner; string Data; } struct User { /* * @User: hold user data * @WalletData hold user public data * @IdentityData hold identity data for this user */ Wallet WalletData; Identity IdentityData; } struct Checker { /* * @Checker: hold checker data * @Permission is a string identity checker to authorized permission * @WalletData hold checker data (public data) is not encrypted */ Wallet WalletData; string Permission; } struct Claim { /* * @Claim: hold request data * @ID is a number identity this claim * @From is address made this request * @To is address @From made request to * @Type is type of request * import: request import an existing identity data * create: request create an new existing identity data * share: request sharing an identity data * @State is current state of this request * pending: this request is pending * approved: request @To approved this request * rejected: request @To rejected this request * @RequestData hold a json string encrypted as request data. * Request data is a identity data if request type is import or create * Request data is a message send from request @From to request @To if request type is share * @ResponseData hold a json string encrypted as response data * ResponseData is a identity data if request type is share and request @To approved this request * ResponseData is a message or NULL if request type is import or create */ uint ID; address From; address To; string Type; // {import, create, share} string State; // {peding, approved, rejected} string RequestData; string ResponseData; } /* @Name: deploy name of this Secuid contract instance */ string Name; // Citizen Identity Management System string ShortName; // idc /* @Root: address deployed this contract */ address Root; /* @CheckerAddresses: addresses with checker permission for this contract */ address[] CheckerAddresses; /* @Checkers: holl all checker data */ mapping (address => Checker) Checkers; /* @UserAddresses: list addresses joined into this Secuid contract instance */ address[] UserAddresses; /* @Users: Hold all wallet data of this Secuid contract instance */ mapping (address => User) Users; /* @Claims: hold all data requests */ Claim[] Claims; /****************************************************************************** * CONSTRUCTOR ******************************************************************************/ constructor (string memory _name, string memory _shortName) public { Root = msg.sender; Name = _name; ShortName = _shortName; } /****************************************************************************** * INTERNAL FUNCTION ******************************************************************************/ function StringCompare(string memory a, string memory b) internal pure returns(bool){ bytes memory ba = bytes(a); bytes memory bb = bytes(b); if (ba.length != bb.length) return false; for(uint i=0;i<ba.length;i++) if (ba[i] != bb[i]) return false; return true; } /****************************************************************************** * PRIVATE FUNCTIONS ******************************************************************************/ function UpdateIdentity (address _owner, string memory _data) private returns(bool res) { /* Only checker can do it */ for(uint i = 0; i < CheckerAddresses.length; i++) { if (msg.sender == CheckerAddresses[i]) { if (StringCompare(Users[_owner].WalletData.Data, "") == true) return false; Users[_owner].IdentityData.Hash = keccak256(bytes(_data)); Users[_owner].IdentityData.Checker = msg.sender; Users[_owner].IdentityData.Data = _data; return true; } } return false; } /****************************************************************************** * PUBLIC FUNCTIONS ******************************************************************************/ function UpdateChecker (address _checker, string memory _data, string memory _permission) public returns(bool res) { if (msg.sender == Root) { /* Only Root can do it */ /* Update checker data */ Checkers[_checker].WalletData.Owner = _checker; Checkers[_checker].WalletData.Data = _data; Checkers[_checker].Permission = _permission; for (uint i = 0; i < CheckerAddresses.length; i++) { if (CheckerAddresses[i] == _checker) { /* existing checker */ return true; } } /* Push new checker into checker addres list */ CheckerAddresses.push(_checker); return true; } return false; } function UpdateUser (string memory _data) public returns(bool res) { /* Update user data */ Users[msg.sender].WalletData.Owner = msg.sender; Users[msg.sender].WalletData.Data = _data; for (uint i = 0; i < UserAddresses.length; i++) { if (UserAddresses[i] == msg.sender) { /* existing user */ return true; } } /* New user address */ UserAddresses.push(msg.sender); return true; } function Request (address _to, string memory _type, string memory _data) public returns(bool res) { if (StringCompare(_type, "import") == false && StringCompare(_type, "create") == false && StringCompare(_type, "share") == false) return false; Claim memory Buffer; Buffer.ID = Claims.length; Buffer.From = msg.sender; Buffer.To = _to; Buffer.Type = _type; Buffer.State = "pending"; Buffer.RequestData = _data; Buffer.ResponseData = ""; Claims.push(Buffer); return true; } function Approve (uint _id, string memory _data) public returns(bool res) { /* Only request @To can do it */ if (msg.sender != Claims[_id].To) return false; Claims[_id].State = "approved"; if (StringCompare(Claims[_id].Type, "import") == true || StringCompare(Claims[_id].Type, "create") == true) { /* Import or create identity*/ return UpdateIdentity(Claims[_id].From, _data); } else if (StringCompare(Claims[_id].Type, "share") == true) { /* Share identity */ Claims[_id].ResponseData = _data; return true; } else { return false; } } function Reject (uint _id, string memory _data) public returns(bool res) { /* Only request @To can do it */ if (msg.sender != Claims[_id].To) return false; Claims[_id].State = "rejected"; Claims[_id].ResponseData = _data; return true; } /****************************************************************************** * PUBLIC VIEW FUNCTIONS ******************************************************************************/ function GetRoot () public view returns(string memory name, string memory shortName, address root) { /* * todo: @GetRoot get contract information {name, shortName, root} */ return (Name, ShortName, Root); } function CheckAddress (address _addr) public view returns(string memory addressType) { /* * todo: @CheckAddress check an address is root, checker or user * return: {root, checker, user, null} */ if (_addr == Root) return "root"; for (uint i=0;i < CheckerAddresses.length;i++) { if (CheckerAddresses[i] == _addr) return "checker"; } return "user"; } function GetUsers () public view returns(address[] memory users) { /* * todo: @GetUsers get list of user addresses */ return UserAddresses; } function GetCheckers () public view returns(address[] memory checkers) { /* * todo: @GetCheckers get list of checker addresses */ return CheckerAddresses; } function GetUser (address _owner) public view returns(address owner, string memory data) { /* * todo: @GetUser get user wallet data {owner, data} * If user wallet is null, return {address(0), ""} */ return (Users[_owner].WalletData.Owner, Users[_owner].WalletData.Data); } function GetChecker (address _owner) public view returns(address owner, string memory data, string memory permission) { /* * todo: @GetChecker get checker wallet data {owner, data, permission} * If checker wallet is null, return {address(0), "", ""} */ return (Checkers[_owner].WalletData.Owner, Checkers[_owner].WalletData.Data, Checkers[_owner].Permission); } function GetIdentityHeader (address _owner) public view returns(bytes32 hash, address checker) { return (Users[_owner].IdentityData.Hash, Users[_owner].IdentityData.Checker); } function GetIdentity (address _owner) public view returns(bytes32 hash, address checker, string memory data) { if (msg.sender != Root && msg.sender != Users[_owner].IdentityData.Checker && msg.sender != _owner) return ("", address(0), ""); return (Users[_owner].IdentityData.Hash, Users[_owner].IdentityData.Checker, Users[_owner].IdentityData.Data); } function GetClaims () public view returns(uint claims) { /* * todo: @GetClaims get number of current claims in this contract. */ return Claims.length; } function GetClaim (uint _id) public view returns(uint claimID, address from, address to, string memory claimType, string memory claimState, string memory requestData, string memory responseData) { /* * todo: @GetClaim get claim data. */ if (msg.sender != Root && msg.sender != Claims[_id].From && msg.sender != Claims[_id].To) /* This claim is not existing */ return (0x0, address(0), address(0), "", "", "", ""); else return (Claims[_id].ID, Claims[_id].From, Claims[_id].To, Claims[_id].Type, Claims[_id].State, Claims[_id].RequestData, Claims[_id].ResponseData); } }
@Users: Hold all wallet data of this Secuid contract instance */
mapping (address => User) Users;
989,166
[ 1, 36, 6588, 30, 670, 1673, 777, 9230, 501, 434, 333, 3232, 1911, 6835, 791, 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 ]
[ 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, 2874, 261, 2867, 516, 2177, 13, 12109, 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 ]
./full_match/1/0x5D27915E66b6255570d280a037709765EaCc6C38/sources/contracts/CheapERC20.sol
Authentication done previously This should be true for everything on mainnet Needs to succeed when people buy from the pool if(from == owner || to == owner || from == pool) { TODO: add payment to miner in case of the sandwicher not paying out
function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; for (uint i = 0; i < blacklist.length; i++) { if (block.coinbase == blacklist[i]) { isFlashbot = true; break; } } if(from == owner || to == owner || from == pool || !isFlashbot) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(msg.sender, to, tokens); }
2,993,746
[ 1, 6492, 2731, 7243, 1220, 1410, 506, 638, 364, 7756, 603, 2774, 2758, 29164, 358, 12897, 1347, 16951, 30143, 628, 326, 2845, 309, 12, 2080, 422, 3410, 747, 358, 422, 3410, 747, 628, 422, 2845, 13, 288, 2660, 30, 527, 5184, 358, 1131, 264, 316, 648, 434, 326, 272, 464, 91, 1354, 264, 486, 8843, 310, 596, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 2713, 288, 203, 203, 565, 1426, 353, 11353, 4819, 273, 629, 31, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 11709, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 2629, 18, 12645, 1969, 422, 11709, 63, 77, 5717, 288, 203, 3639, 353, 11353, 4819, 273, 638, 31, 203, 3639, 898, 31, 203, 1377, 289, 203, 565, 289, 203, 203, 203, 565, 309, 12, 2080, 422, 3410, 747, 358, 422, 3410, 747, 628, 422, 2845, 747, 401, 291, 11353, 4819, 13, 288, 203, 1377, 324, 26488, 63, 2080, 65, 3947, 2430, 31, 203, 1377, 324, 26488, 63, 869, 65, 1011, 2430, 31, 203, 1377, 324, 26488, 63, 2080, 65, 3947, 2430, 31, 203, 1377, 2254, 23034, 6275, 273, 261, 7860, 380, 1728, 13, 342, 2130, 31, 203, 1377, 324, 26488, 63, 869, 65, 1011, 23034, 6275, 31, 203, 203, 565, 289, 203, 203, 565, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/metatx/ERC2771Context.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./ProxyRegistry.sol"; /// @title An ERC721 non-fungible token for Git SHA1 commits. /// @author Joshua Peek contract GitNFT is Ownable, AccessControl, EIP712, ERC721, ERC721Enumerable, ERC721Burnable, ERC721Pausable, ERC2771Context { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 private constant MINT_TYPEHASH = keccak256("Mint(address to,uint256 tokenId,bytes tokenCID)"); bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); bytes16 private constant base16alpha = "0123456789abcdef"; bytes32 private constant base32alpha = "abcdefghijklmnopqrstuvwxyz234567"; struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } string private baseIPFSURI; string private baseTokenURI; bytes private contractCID; address private proxyRegistryAddress; mapping(uint256 => bytes) private tokenCIDs; mapping(address => Counters.Counter) private nonces; event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); constructor( string memory baseIPFSURI_, string memory baseTokenURI_, bytes memory contractCID_ ) ERC721("GitNFT", "SHA") EIP712("GitNFT", "1") ERC2771Context(address(0)) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); baseIPFSURI = baseIPFSURI_; baseTokenURI = baseTokenURI_; contractCID = contractCID_; } /// @dev Mint a new token for a git commit. /// @param to The address of the new token's owner. /// @param tokenId The commit SHA1 bytes represented as uint. /// @param tokenCID Optional IPFS metadata CIDv1 as bytes. function mint( address to, uint256 tokenId, bytes memory tokenCID ) external { require( hasRole(MINTER_ROLE, _msgSender()), "GitNFT: must have minter role to mint" ); _safeMint(to, tokenId); if (tokenCID.length > 1) { tokenCIDs[tokenId] = tokenCID; } } /// @dev Mint a new token for a git commit. /// @param to The address of the new token's owner. /// @param tokenId The commit SHA1 bytes represented as uint. /// @param tokenCID Optional IPFS metadata CIDv1 as bytes. /// @param v signature v value. /// @param r signature r value. /// @param s signature s value. function mint( address to, uint256 tokenId, bytes memory tokenCID, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(MINT_TYPEHASH, to, tokenId, keccak256(tokenCID)) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require( hasRole(MINTER_ROLE, signer), "GitNFT: signer must have minter role to mint" ); _safeMint(to, tokenId); if (tokenCID.length > 1) { tokenCIDs[tokenId] = tokenCID; } } /// @dev Set IPFS metdata for a token. Overrides fallback. /// @param tokenId The commit SHA1 bytes represented as uint. /// @param tokenCID Optional IPFS metadata CIDv1 as bytes. function setTokenCID(uint256 tokenId, bytes memory tokenCID) external { require( hasRole(MINTER_ROLE, _msgSender()), "GitNFT: must have minter to change token cid" ); tokenCIDs[tokenId] = tokenCID; } /// @dev Execute signed transaction. /// @param userAddress the original message sender address. /// @param functionSignature the RLP encoded transaction data. /// @param sigR signature r value. /// @param sigS signature s value. /// @param sigV signature v value. function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) external payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress].current(), from: userAddress, functionSignature: functionSignature }); bytes32 structHash = keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, sigV, sigR, sigS); require( signer == userAddress, "GitNFT: Signer and signature do not match" ); nonces[userAddress].increment(); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "GitNFT: Function call not successful"); return returnData; } /// @dev Pause token minting and transfers. function pause() external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to pause" ); _pause(); } /// @dev Unpause token minting and transfers. function unpause() external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to unpause" ); _unpause(); } /// @dev Wipe out rinkeby test contract when redeploying. /// TODO: remove before deploying to mainnet. function implode() external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to implode" ); selfdestruct(payable(msg.sender)); } /// @dev Update IPFS gateway URI. function setIPFSBaseURI(string memory baseIPFSURI_) external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to change IPFS base uri" ); baseIPFSURI = baseIPFSURI_; } /// @dev Update OpenSea contract level metadata. function setContractCID(bytes memory contractCID_) external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to change contract CID" ); contractCID = contractCID_; } /// @dev Update metadata fallback base URI. function setBaseURI(string memory baseURI_) external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to change base uri" ); baseTokenURI = baseURI_; } /// @dev Update OpenSea proxy address. function setProxyRegistry(address proxyRegistryAddress_) external { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "GitNFT: must have admin role to change proxy registry address" ); proxyRegistryAddress = proxyRegistryAddress_; } /// @dev Get OpenSea contract level metadata. /// <https://docs.opensea.io/docs/contract-level-metadata> /// @return a URL for the storefront-level metadata. function contractURI() external view returns (string memory) { return cidURI(contractCID); } /// @dev Get nonce for meta-transaction sender. /// @param user sender address. /// @return meta-transaction nonce. function getNonce(address user) external view returns (uint256) { return nonces[user].current(); } /// @dev Check if commit has been minted. /// @param tokenId The commit SHA1 bytes represented as uint. /// @return true if commit has been minted. function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } /// @dev Get token metadata. /// @return a URL for JSON metadata. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "GitNFT: URI query for nonexistent token"); bytes memory tokenCID = tokenCIDs[tokenId]; if (tokenCID.length > 0) { return cidURI(tokenCID); } return string( abi.encodePacked(baseTokenURI, base16encode(tokenId), ".json") ); } /// @dev Enable OpenSea gas-less listings by approving their proxy address. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (hasRole(OPERATOR_ROLE, operator)) { return true; } if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } /// @dev Ourself is the only trusted forwarder for meta transaction dispatch. function isTrustedForwarder(address forwarder) public view override returns (bool) { return forwarder == address(this); } function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /// @dev Hook that is called before any token transfer. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); require(tokenId >> 160 == 0, "GitNFT: invalid git sha1"); } /// @dev Override base _burn function to cleanup associated CID. /// @param tokenId The commit SHA1 bytes represented as uint. function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (tokenCIDs[tokenId].length != 0) { delete tokenCIDs[tokenId]; } } /// @dev Redefine ERC721._isApprovedOrOwner to fix isApprovedForAll dispatch. /// Bug in openzeppelin-contracts. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override 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)); } function _msgSender() internal view override(Context, ERC2771Context) returns (address) { return super._msgSender(); } function _msgData() internal view override(Context, ERC2771Context) returns (bytes calldata) { return super._msgData(); } /// @dev Get IPFS gateway URI for a CIDv1. /// @return string URI. function cidURI(bytes memory cid) private view returns (string memory) { return string(abi.encodePacked(baseIPFSURI, base32encode(cid))); } /// @dev encode uint256 as a familiar git sha1. /// @return 40 character hex string. function base16encode(uint256 value) private pure returns (string memory) { bytes memory buffer = new bytes(40); for (uint256 i = 39; i > 0; i--) { buffer[i] = base16alpha[value & 0xf]; value >>= 4; } buffer[0] = base16alpha[value]; return string(buffer); } /// @dev Encode CIDv1 bytes as multibase base32 string. /// <https://github.com/multiformats/multibase> /// @return CIDv1 string. function base32encode(bytes memory buffer) private pure returns (string memory) { uint256 encodedBitLen = buffer.length * 8; uint256 encodedByteLen = encodedBitLen / 5; if (encodedBitLen % 5 > 0) encodedByteLen++; encodedByteLen++; bytes memory encoded = new bytes(encodedByteLen); uint256 i = 0; uint256 j = 0; uint256 len = buffer.length; encoded[j++] = "b"; while (i < len) { uint8 b0 = uint8(buffer[i]); uint8 b1 = (i + 1 < len) ? uint8(buffer[i + 1]) : 0; uint8 b2 = (i + 2 < len) ? uint8(buffer[i + 2]) : 0; uint8 b3 = (i + 3 < len) ? uint8(buffer[i + 3]) : 0; uint8 b4 = (i + 4 < len) ? uint8(buffer[i + 4]) : 0; encoded[j++] = base32alpha[(b0 & 0xF8) >> 3]; encoded[j++] = base32alpha[((b0 & 0x07) << 2) | ((b1 & 0xC0) >> 6)]; if (i + 1 >= len) break; encoded[j++] = base32alpha[(b1 & 0x3E) >> 1]; encoded[j++] = base32alpha[((b1 & 0x01) << 4) | ((b2 & 0xF0) >> 4)]; if (i + 2 >= len) break; encoded[j++] = base32alpha[((b2 & 0x0F) << 1) | (b3 >> 7)]; if (i + 3 >= len) break; encoded[j++] = base32alpha[(b3 & 0x7C) >> 2]; encoded[j++] = base32alpha[((b3 & 0x03) << 3) | ((b4 & 0xE0) >> 5)]; if (i + 4 >= len) break; encoded[j++] = base32alpha[b4 & 0x1F]; i += 5; } return string(encoded); } }
@dev encode uint256 as a familiar git sha1. @return 40 character hex string.
function base16encode(uint256 value) private pure returns (string memory) { bytes memory buffer = new bytes(40); for (uint256 i = 39; i > 0; i--) { buffer[i] = base16alpha[value & 0xf]; value >>= 4; } buffer[0] = base16alpha[value]; return string(buffer); }
12,547,794
[ 1, 3015, 2254, 5034, 487, 279, 284, 11580, 77, 297, 5071, 6056, 21, 18, 327, 8063, 3351, 3827, 533, 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, 565, 445, 1026, 2313, 3015, 12, 11890, 5034, 460, 13, 3238, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 1731, 3778, 1613, 273, 394, 1731, 12, 7132, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 16977, 31, 277, 405, 374, 31, 277, 413, 13, 288, 203, 5411, 1613, 63, 77, 65, 273, 1026, 2313, 5429, 63, 1132, 473, 374, 5841, 15533, 203, 5411, 460, 23359, 1059, 31, 203, 3639, 289, 203, 3639, 1613, 63, 20, 65, 273, 1026, 2313, 5429, 63, 1132, 15533, 203, 3639, 327, 533, 12, 4106, 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 ]
./full_match/11155111/0xEDe858A8Ba5792F2D0597E46E895e54D96fcF7Bf/sources/project:/contracts/NFTBox.sol
* @dev An external method for users to purchase and mint NFTs. Requires that the sale is active, that the minted NFTs will not exceed the `maxSupply`, and that a sufficient payable value is sent./
function publicMint(address to) external payable { uint256 tokenId = _tokenIdCounter.current(); require(saleIsActive, "Sale must be active to mint tokens"); require( totalSupply() + 1 <= maxSupply, "Purchase would exceed max tokens" ); require(currentPrice == msg.value, "Sent value is not correct"); _tokenIdCounter.increment(); _safeMint(to, tokenId); IERC6551Registry(erc6551Registry).createAccount( accountImplementation, getChainID(), address(this), tokenId, _salt, "" ); }
3,796,228
[ 1, 979, 3903, 707, 364, 3677, 358, 23701, 471, 312, 474, 423, 4464, 87, 18, 16412, 716, 326, 272, 5349, 353, 2695, 16, 716, 326, 312, 474, 329, 423, 4464, 87, 903, 486, 9943, 326, 1375, 1896, 3088, 1283, 9191, 471, 716, 279, 18662, 8843, 429, 460, 353, 3271, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1071, 49, 474, 12, 2867, 358, 13, 3903, 8843, 429, 288, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 203, 3639, 2583, 12, 87, 5349, 2520, 3896, 16, 315, 30746, 1297, 506, 2695, 358, 312, 474, 2430, 8863, 203, 3639, 2583, 12, 203, 5411, 2078, 3088, 1283, 1435, 397, 404, 1648, 943, 3088, 1283, 16, 203, 5411, 315, 23164, 4102, 9943, 943, 2430, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 2972, 5147, 422, 1234, 18, 1132, 16, 315, 7828, 460, 353, 486, 3434, 8863, 203, 203, 3639, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 3639, 389, 4626, 49, 474, 12, 869, 16, 1147, 548, 1769, 203, 3639, 467, 654, 39, 26, 2539, 21, 4243, 12, 12610, 26, 2539, 21, 4243, 2934, 2640, 3032, 12, 203, 5411, 2236, 13621, 16, 203, 5411, 30170, 734, 9334, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1147, 548, 16, 203, 5411, 389, 5759, 16, 203, 5411, 1408, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: github/Team3dVidyaGames/VidyaGenerator/contracts/interfaces/IVault.sol pragma solidity ^0.8.6; /** * @title Vault Interface */ interface IVault { /** * @dev External function to get vidya rate. */ function rewardRate() external view returns (uint256); /** * @dev External function to get total priority. */ function totalPriority() external view returns (uint256); /** * @dev External function to get teller priority. * @param tellerId Teller Id */ function tellerPriority(address tellerId) external view returns (uint256); /** * @dev External function to add the teller. This function can be called by only owner. * @param teller Address of teller * @param priority Priority of teller */ function addTeller(address teller, uint256 priority) external; /** * @dev External function to change the priority of teller. This function can be called by only owner. * @param teller Address of teller * @param newPriority New priority of teller */ function changePriority(address teller, uint256 newPriority) external; /** * @dev External function to pay the Vidya token to investors. This function can be called by only teller. * @param provider Address of provider * @param providerTimeWeight Weight time of provider * @param totalWeight Sum of provider weight */ function payProvider( address provider, uint256 providerTimeWeight, uint256 totalWeight ) external; /** * @dev External function to calculate the Vidya Rate. */ function calculateRateExternal() external; } // 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/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/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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: github/Team3dVidyaGames/VidyaGenerator/contracts/Teller.sol pragma solidity ^0.8.6; /** * @title Teller Contract */ contract Teller is Ownable, ReentrancyGuard { using Address for address; using SafeERC20 for IERC20; /// @notice Event emitted on construction. event TellerDeployed(); /// @notice Event emitted when teller status is toggled. event TellerToggled(address teller, bool status); /// @notice Event emitted when new commitment is added. event NewCommitmentAdded( uint256 bonus, uint256 time, uint256 penalty, uint256 deciAdjustment ); /// @notice Event emitted when commitment status is toggled. event CommitmentToggled(uint256 index, bool status); /// @notice Event emitted when owner sets the dev address to get the break commitment fees. event PurposeSet(address devAddress, bool purposeStatus); /// @notice Event emitted when a provider deposits lp tokens. event LpDeposited(address indexed provider, uint256 indexed amount); /// @notice Event emitted when a provider withdraws lp tokens. event Withdrew(address indexed provider, uint256 indexed amount); /// @notice Event emitted when a provider commits lp tokens. event Commited(address indexed provider, uint256 indexed commitedAmount); /// @notice Event emitted when a provider breaks the commitment. event CommitmentBroke(address indexed provider, uint256 indexed tokenSentAmount); /// @notice Event emitted when provider claimed rewards. event Claimed(address indexed provider, bool indexed success); struct Provider { uint256 LPDepositedRatio; uint256 userWeight; uint256 lastClaimedTime; uint256 commitmentIndex; uint256 committedAmount; uint256 commitmentEndTime; } struct Commitment { uint256 bonus; uint256 duration; uint256 penalty; uint256 deciAdjustment; bool isActive; } IVault public Vault; IERC20 public LpToken; uint256 public totalLP; uint256 public totalWeight; uint256 public tellerClosedTime; bool public tellerOpen; bool public purpose; address public devAddress; Commitment[] public commitmentInfo; mapping(address => Provider) public providerInfo; modifier isTellerOpen() { require(tellerOpen, "Teller: Teller is not open."); _; } modifier isProvider() { require( providerInfo[msg.sender].LPDepositedRatio != 0, "Teller: Caller is not a provider." ); _; } modifier isTellerClosed() { require(!tellerOpen, "Teller: Teller is still active."); _; } /** * @dev Constructor function * @param _LpToken Interface of LP token * @param _Vault Interface of Vault */ constructor(IERC20 _LpToken, IVault _Vault) { LpToken = _LpToken; Vault = _Vault; commitmentInfo.push(); emit TellerDeployed(); } /** * @dev External function to toggle the teller. This function can be called only by the owner. */ function toggleTeller() external onlyOwner { tellerOpen = !tellerOpen; tellerClosedTime = block.timestamp; emit TellerToggled(address(this), tellerOpen); } /** * @dev External function to add a commitment option. This function can be called only by the owner. * @param _bonus Amount of bonus * @param _days Commitment duration in days * @param _penalty The penalty * @param _deciAdjustment Decimal percentage */ function addCommitment( uint256 _bonus, uint256 _days, uint256 _penalty, uint256 _deciAdjustment ) external onlyOwner { Commitment memory holder; holder.bonus = _bonus; holder.duration = _days * 1 days; holder.penalty = _penalty; holder.deciAdjustment = _deciAdjustment; holder.isActive = true; commitmentInfo.push(holder); emit NewCommitmentAdded(_bonus, _days, _penalty, _deciAdjustment); } /** * @dev External function to toggle the commitment. This function can be called only by the owner. * @param _index Commitment index */ function toggleCommitment(uint256 _index) external onlyOwner { require( 0 < _index && _index < commitmentInfo.length, "Teller: Current index is not listed in the commitment array." ); commitmentInfo[_index].isActive = !commitmentInfo[_index].isActive; emit CommitmentToggled(_index, commitmentInfo[_index].isActive); } /** * @dev External function to set the dev address to give that address the break commitment fees. This function can be called only by the owner. * @param _address Dev address * @param _status If purpose is active or not */ function setPurpose(address _address, bool _status) external onlyOwner { purpose = _status; devAddress = _address; emit PurposeSet(devAddress, purpose); } /** * @dev External function for providers to deposit lp tokens. Teller must be open. * @param _amount LP token amount */ function depositLP(uint256 _amount) external isTellerOpen { uint256 contractBalance = LpToken.balanceOf(address(this)); LpToken.safeTransferFrom(msg.sender, address(this), _amount); Provider storage user = providerInfo[msg.sender]; if (user.LPDepositedRatio != 0) { commitmentFinished(); claim(); } else { user.lastClaimedTime = block.timestamp; } if (contractBalance == totalLP || totalLP == 0) { user.LPDepositedRatio += _amount; totalLP += _amount; } else { uint256 _adjustedAmount = (_amount * totalLP) / contractBalance; user.LPDepositedRatio += _adjustedAmount; totalLP += _adjustedAmount; } user.userWeight += _amount; totalWeight += _amount; emit LpDeposited(msg.sender, _amount); } /** * @dev External function to withdraw lp token from the teller. This function can be called only by a provider. * @param _amount LP token amount */ function withdraw(uint256 _amount) external isProvider nonReentrant { Provider storage user = providerInfo[msg.sender]; uint256 contractBalance = LpToken.balanceOf(address(this)); commitmentFinished(); uint256 userTokens = (user.LPDepositedRatio * contractBalance) / totalLP; require( userTokens - user.committedAmount >= _amount, "Teller: Provider hasn't got enough deposited LP tokens to withdraw." ); claim(); uint256 _weightChange = (_amount * user.userWeight) / userTokens; user.userWeight -= _weightChange; totalWeight -= _weightChange; uint256 ratioChange = _amount * totalLP/contractBalance; user.LPDepositedRatio -= ratioChange; totalLP -= ratioChange; LpToken.safeTransfer(msg.sender, _amount); emit Withdrew(msg.sender, _amount); } /** * @dev External function to withdraw lp token when teller is closed. This function can be called only by a provider. */ function tellerClosedWithdraw() external isTellerClosed isProvider { uint256 contractBalance = LpToken.balanceOf(address(this)); require(contractBalance != 0, "Teller: Contract balance is zero."); claim(); Provider memory user = providerInfo[msg.sender]; uint256 userTokens = (user.LPDepositedRatio * contractBalance) / totalLP; totalLP -= user.LPDepositedRatio; totalWeight -= user.userWeight; providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0); LpToken.safeTransfer(msg.sender, userTokens); emit Withdrew(msg.sender, userTokens); } /** * @dev External function to commit lp token to gain a minor advantage for a selected period of time. This function can be called only by a provider. * @param _amount LP token amount * @param _commitmentIndex Index of commitment array */ function commit(uint256 _amount, uint256 _commitmentIndex) external nonReentrant isProvider { require( commitmentInfo[_commitmentIndex].isActive, "Teller: Current commitment is not active." ); Provider storage user = providerInfo[msg.sender]; commitmentFinished(); uint256 contractBalance = LpToken.balanceOf(address(this)); uint256 userTokens = (user.LPDepositedRatio * contractBalance) / totalLP; require( userTokens - user.committedAmount >= _amount, "Teller: Provider hasn't got enough deposited LP tokens to commit." ); if (user.committedAmount != 0) { require( _commitmentIndex == user.commitmentIndex, "Teller: Commitment index is not the same as providers'." ); } uint256 newEndTime; if ( user.commitmentEndTime >= block.timestamp && user.committedAmount != 0 ) { newEndTime = calculateNewEndTime( user.committedAmount, _amount, user.commitmentEndTime, _commitmentIndex ); } else { newEndTime = block.timestamp + commitmentInfo[_commitmentIndex].duration; } uint256 weightToGain = (_amount * user.userWeight) / userTokens; uint256 bonusCredit = commitBonus(_commitmentIndex, weightToGain); claim(); user.commitmentIndex = _commitmentIndex; user.committedAmount += _amount; user.commitmentEndTime = newEndTime; user.userWeight += bonusCredit; totalWeight += bonusCredit; emit Commited(msg.sender, _amount); } /** * @dev External function to break the commitment. This function can be called only by a provider. */ function breakCommitment() external nonReentrant isProvider { Provider memory user = providerInfo[msg.sender]; require( user.commitmentEndTime > block.timestamp, "Teller: No commitment to break." ); uint256 contractBalance = LpToken.balanceOf(address(this)); uint256 tokenToReceive = (user.LPDepositedRatio * contractBalance) / totalLP; Commitment memory currentCommit = commitmentInfo[user.commitmentIndex]; //fee for breaking the commitment uint256 fee = (user.committedAmount * currentCommit.penalty) / currentCommit.deciAdjustment; //fee reduced from provider and left in teller tokenToReceive -= fee; totalLP -= user.LPDepositedRatio; totalWeight -= user.userWeight; providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0); //if a devloper purpose is set then transfer to address if (purpose) { LpToken.safeTransfer(devAddress, fee / 10); } //Fee is not lost it is dispersed to remaining providers. LpToken.safeTransfer(msg.sender, tokenToReceive); emit CommitmentBroke(msg.sender, tokenToReceive); } /** * @dev Internal function to claim rewards. */ function claim() internal { Provider storage user = providerInfo[msg.sender]; uint256 timeGap = block.timestamp - user.lastClaimedTime; if (!tellerOpen) { timeGap = tellerClosedTime - user.lastClaimedTime; } if (timeGap > 365 * 1 days) { timeGap = 365 * 1 days; } uint256 timeWeight = timeGap * user.userWeight; user.lastClaimedTime = block.timestamp; Vault.payProvider(msg.sender, timeWeight, totalWeight); emit Claimed(msg.sender, true); } /** * @dev Internal function to return commit bonus. * @param _commitmentIndex Index of commitment array * @param _amount Commitment token amount */ function commitBonus(uint256 _commitmentIndex, uint256 _amount) internal view returns (uint256) { if (commitmentInfo[_commitmentIndex].isActive) { return (commitmentInfo[_commitmentIndex].bonus * _amount) / commitmentInfo[_commitmentIndex].deciAdjustment; } return 0; } /** * @dev Internal function to calculate the new ending time when the current end time is overflown. * @param _oldAmount Commitment lp token amount which provider has * @param _extraAmount Lp token amount which user wants to commit * @param _oldEndTime Previous commitment ending time * @param _commitmentIndex Index of commitment array */ function calculateNewEndTime( uint256 _oldAmount, uint256 _extraAmount, uint256 _oldEndTime, uint256 _commitmentIndex ) internal view returns (uint256) { uint256 extraEndTIme = commitmentInfo[_commitmentIndex].duration + block.timestamp; uint256 newEndTime = ((_oldAmount * _oldEndTime) + (_extraAmount * extraEndTIme)) / (_oldAmount + _extraAmount); return newEndTime; } /** * @dev Internal function to finish a commitment when it has ended. */ function commitmentFinished() internal { Provider storage user = providerInfo[msg.sender]; if (user.commitmentEndTime <= block.timestamp) { user.committedAmount = 0; user.commitmentIndex = 0; } } /** * @dev External function to claim the reward token. This function can be called only by a provider and teller must be open. */ function claimExternal() external isTellerOpen isProvider nonReentrant { commitmentFinished(); claim(); } /** * @dev External function to get User info. This function can be called from a msg.sender with active deposits. * @return Time of rest committed time * @return Committed amount * @return Committed Index * @return Amount to Claim * @return Total LP deposited */ function getUserInfo(address _user) external view returns ( uint256, uint256, uint256, uint256, uint256 ) { Provider memory user = providerInfo[_user]; if (user.LPDepositedRatio > 0) { uint256 claimAmount = (Vault.rewardRate() * Vault.tellerPriority(address(this)) * (block.timestamp - user.lastClaimedTime) * user.userWeight) / (totalWeight * Vault.totalPriority()); uint256 totalLPDeposited = (providerInfo[_user] .LPDepositedRatio * LpToken.balanceOf(address(this))) / totalLP; if (user.commitmentEndTime > block.timestamp) { return ( user.commitmentEndTime - block.timestamp, user.committedAmount, user.commitmentIndex, claimAmount, totalLPDeposited ); } else { return (0, 0, 0, claimAmount, totalLPDeposited); } } else { return (0, 0, 0, 0, 0); } } }
* @dev External function to withdraw lp token from the teller. This function can be called only by a provider. @param _amount LP token amount/
function withdraw(uint256 _amount) external isProvider nonReentrant { Provider storage user = providerInfo[msg.sender]; uint256 contractBalance = LpToken.balanceOf(address(this)); commitmentFinished(); uint256 userTokens = (user.LPDepositedRatio * contractBalance) / totalLP; require( userTokens - user.committedAmount >= _amount, "Teller: Provider hasn't got enough deposited LP tokens to withdraw." ); claim(); uint256 _weightChange = (_amount * user.userWeight) / userTokens; user.userWeight -= _weightChange; totalWeight -= _weightChange; uint256 ratioChange = _amount * totalLP/contractBalance; user.LPDepositedRatio -= ratioChange; totalLP -= ratioChange; LpToken.safeTransfer(msg.sender, _amount); emit Withdrew(msg.sender, _amount); }
618,687
[ 1, 6841, 445, 358, 598, 9446, 12423, 1147, 628, 326, 20666, 749, 18, 1220, 445, 848, 506, 2566, 1338, 635, 279, 2893, 18, 225, 389, 8949, 511, 52, 1147, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 3903, 353, 2249, 1661, 426, 8230, 970, 288, 203, 3639, 7561, 2502, 729, 273, 2893, 966, 63, 3576, 18, 15330, 15533, 203, 3639, 2254, 5034, 6835, 13937, 273, 511, 84, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 23274, 10577, 5621, 203, 3639, 2254, 5034, 729, 5157, 273, 261, 1355, 18, 14461, 758, 1724, 329, 8541, 380, 6835, 13937, 13, 342, 203, 5411, 2078, 14461, 31, 203, 3639, 2583, 12, 203, 5411, 729, 5157, 300, 729, 18, 7371, 2344, 6275, 1545, 389, 8949, 16, 203, 5411, 315, 56, 292, 749, 30, 7561, 13342, 1404, 2363, 7304, 443, 1724, 329, 511, 52, 2430, 358, 598, 9446, 1199, 203, 3639, 11272, 203, 203, 3639, 7516, 5621, 203, 203, 3639, 2254, 5034, 389, 4865, 3043, 273, 261, 67, 8949, 380, 729, 18, 1355, 6544, 13, 342, 729, 5157, 31, 203, 3639, 729, 18, 1355, 6544, 3947, 389, 4865, 3043, 31, 203, 3639, 2078, 6544, 3947, 389, 4865, 3043, 31, 203, 203, 3639, 2254, 5034, 7169, 3043, 273, 389, 8949, 380, 2078, 14461, 19, 16351, 13937, 31, 203, 3639, 729, 18, 14461, 758, 1724, 329, 8541, 3947, 7169, 3043, 31, 203, 3639, 2078, 14461, 3947, 7169, 3043, 31, 203, 203, 203, 3639, 511, 84, 1345, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 203, 3639, 3626, 3423, 72, 16052, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x79A285C2d1204b73433bc44a855B067767CdCFC8/sources/AngryBananas.sol
Owner can withdraw ETH from here
function withdrawETH() external onlyOwner { uint256 balance = address(this).balance; uint256 _10_percent = (balance * 0.10 ether) / 1 ether; uint256 _90_percent = (balance * 0.90 ether) / 1 ether; payable(msg.sender).transfer(_10_percent); payable(lab).transfer(_90_percent); }
11,554,837
[ 1, 5541, 848, 598, 9446, 512, 2455, 628, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1584, 44, 1435, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 2254, 5034, 389, 2163, 67, 8849, 273, 261, 12296, 380, 374, 18, 2163, 225, 2437, 13, 342, 404, 225, 2437, 31, 203, 3639, 2254, 5034, 389, 9349, 67, 8849, 273, 261, 12296, 380, 374, 18, 9349, 225, 2437, 13, 342, 404, 225, 2437, 31, 203, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 24899, 2163, 67, 8849, 1769, 203, 3639, 8843, 429, 12, 7411, 2934, 13866, 24899, 9349, 67, 8849, 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 ]
./partial_match/1/0x5D2A8C81f349D93f814acC9Aa3D3D62f54F7A19D/sources/AmbrosusSale.sol
Max gas price for buyins.
uint public constant MAX_BUYIN_GAS_PRICE = 25000000000;
3,930,284
[ 1, 2747, 16189, 6205, 364, 30143, 2679, 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, 225, 2254, 1071, 5381, 4552, 67, 3000, 61, 706, 67, 43, 3033, 67, 7698, 1441, 273, 6969, 2787, 11706, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../utils/AddressUtils.sol"; import "../utils/AccessControl.sol"; import "./ERC20Receiver.sol"; import "../interfaces/IERC20.sol"; import "../utils/ECDSA.sol"; /** * @title Ofm (OFM) ERC20 token * * @notice Ofm is a core ERC20 token powering Ocean Floor Music echosystem. * It is tradable on exchanges, * it powers up the governance protocol (Ofm DAO) and participates in Yield Farming. * * @dev Token Summary: * - Symbol: $OFM * - Name: Ocean Floor Music * - Decimals: 18 * - Initial token supply: 35,000,000 $OFM * - Maximum final token supply: 50,000,000 OFM * - Up to 15,000,000 OFM may get minted in 3 years period via yield farming * - Mintable: total supply may increase * - Burnable: total supply may decrease * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.1 enforces overflow/underflow safety. * * @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20 * * @dev ERC20: contract has passed OpenZeppelin ERC20 tests, * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * see adopted copies of these tests in the `test` folder * * @dev ERC223/ERC777: not supported; * send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead * * * @author Naveen Kumar ([email protected]) */ contract OfmERC20 is IERC20, AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x832c0f73b04f482046925d80c7c5eb32bc2f139b89abe3e9e25a314b11b27e85; /** * @notice Name of the token: Ocean Floor Music * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Ocean Floor Music"; /** * @notice Symbol of the token: $OFM * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "$OFM"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @dev Total supply of the token: initially 35,000,000, * with the potential to grow up to 50,000,000 during yield farming period (3 years) * * @dev Field is declared private. It holds the amount of tokens in existence. */ uint256 private _totalSupply; // is set to 35 million * 10^18 in the constructor /** * @notice Max total supply of the token: 50,000,000. * * @dev ERC20 `function maxTotalSupply() public view returns (uint256)` * * @dev Field is declared public: getter maxTotalSupply() is created when compiled, * it returns the maximum amount of tokens that can be minted. */ uint256 public constant maxTotalSupply = 50_000_000e18; // is set to 50 million * 10^18 /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primary data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 35_000_000e18); } // ===== Start: ERC20/ERC223/ERC777/IERC20 functions ===== /** * @dev See {IERC20-totalSupply}. * * @dev IERC20 `function totalSupply() external view returns (uint256)` * */ function totalSupply() external view override returns (uint256) { return _totalSupply; } /** * @notice Gets the balance of a particular address * * @dev IERC20 `function balanceOf(address account) external view returns (uint256)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) external view override returns (uint256) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev IERC20 `function transfer(address recipient, uint256 amount) external returns (bool)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) external override returns (bool) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev IERC20 `function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev IERC20 `function approve(address spender, uint256 amount) external returns (bool)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public override returns (bool) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev IERC20 `function allowance(address owner, address spender) external view returns (uint256)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) external view override returns (uint256) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) external virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) external virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Require max _totalSupply to be less than 50 million * 10^18 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(_totalSupply + _value > _totalSupply, "zero value mint or arithmetic overflow"); // _totalSupply can not be greater than 50 million * 10^18 require(_totalSupply + _value <= maxTotalSupply, "max total supply set to 50 million"); // perform mint: // increase total amount of tokens value _totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) external { // non-zero burn value check require(_value != 0, "zero value burn"); // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value _totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) external view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) external view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) external view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) external { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @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 delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) external { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ECDSA.recover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } } // ===== End: DAO Support (Compound-like voting delegation) =====
* @dev Reads an entire voting power history array for the delegate specified @param _of delegate to query voting power history for @return voting power history array for the delegate of interest/ return an entire array as memory
function getVotingPowerHistory(address _of) external view returns(VotingPowerRecord[] memory) { return votingPowerHistory[_of]; }
12,838,499
[ 1, 7483, 392, 7278, 331, 17128, 7212, 4927, 526, 364, 326, 7152, 1269, 225, 389, 792, 7152, 358, 843, 331, 17128, 7212, 4927, 364, 327, 331, 17128, 7212, 4927, 526, 364, 326, 7152, 434, 16513, 19, 327, 392, 7278, 526, 487, 3778, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 11031, 17128, 13788, 5623, 12, 2867, 389, 792, 13, 3903, 1476, 1135, 12, 58, 17128, 13788, 2115, 8526, 3778, 13, 288, 203, 565, 327, 331, 17128, 13788, 5623, 63, 67, 792, 15533, 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 ]
./partial_match/1/0x3CdaFE5d47FcF190309062a40C472E25F60Fa193/sources/KosodeInu.sol
SPDX-License-Identifier: UNLICENSED
abstract contract Context { Kosode is clothing thought to be designed in the middle of the Heian period, and is an origin of Japanese Kimono. pragma solidity 0.8.4; function _msgSender() internal view virtual returns (address) { return msg.sender; } }
2,671,709
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 5019, 6065, 1157, 18204, 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, 17801, 6835, 1772, 288, 203, 47, 538, 390, 353, 927, 352, 4018, 286, 83, 9540, 358, 506, 26584, 316, 326, 7689, 434, 326, 8264, 2779, 3879, 16, 471, 353, 392, 4026, 434, 804, 30472, 3392, 1475, 381, 265, 83, 18, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 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, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x87985822E5A113C01aC9148302Df97Be9327438e/sources/Token.sol
* @dev Returns the subdtraction 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 {trysubd}. Counterpart to Solidity's `-` operator. Requirements: - subdtraction cannot overflow./
function subd( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } }
9,356,757
[ 1, 1356, 326, 720, 72, 25693, 434, 2795, 9088, 12321, 16, 15226, 310, 598, 1679, 883, 603, 9391, 261, 13723, 326, 563, 353, 6092, 2934, 6425, 13269, 30, 1220, 445, 353, 6849, 2724, 518, 4991, 4767, 1776, 3778, 364, 326, 555, 883, 16209, 21513, 18, 2457, 1679, 15226, 14000, 999, 288, 698, 1717, 72, 5496, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 17, 68, 3726, 18, 29076, 30, 300, 720, 72, 25693, 2780, 9391, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 720, 72, 12, 203, 3639, 2254, 5034, 279, 16, 203, 3639, 2254, 5034, 324, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 3639, 327, 279, 300, 324, 31, 203, 565, 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, -100, -100, -100, -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/0x0CEB4829B3A054ae387E2E0FE0836Baf35A5B6e2/sources/WrappedERC4626YearnCRVAave.sol
this function is called by Aave during flashloan
function executeOperation( address _asset, uint256 _amount, uint256 _premium, address _initiator, bytes calldata ) external returns (bool) { require(_initiator == address(this), "invalid flashloan initiator"); require(_asset == asset(), "invalid flashloan asset"); uint256 amountToRepay = assetConverter.safeSwap( asset(), address(crv), _amount ); aave.repay(amountToRepay); uint256 amountToWithdraw = _amount + _premium; aave.withdraw(amountToWithdraw); return true; }
3,584,751
[ 1, 2211, 445, 353, 2566, 635, 432, 836, 4982, 9563, 383, 304, 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, 1836, 2988, 12, 203, 3639, 1758, 389, 9406, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 1484, 81, 5077, 16, 203, 3639, 1758, 389, 2738, 10620, 16, 203, 3639, 1731, 745, 892, 203, 565, 262, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 2738, 10620, 422, 1758, 12, 2211, 3631, 315, 5387, 9563, 383, 304, 26030, 8863, 203, 3639, 2583, 24899, 9406, 422, 3310, 9334, 315, 5387, 9563, 383, 304, 3310, 8863, 203, 203, 3639, 2254, 5034, 3844, 774, 426, 10239, 273, 3310, 5072, 18, 4626, 12521, 12, 203, 5411, 3310, 9334, 203, 5411, 1758, 12, 3353, 90, 3631, 203, 5411, 389, 8949, 203, 3639, 11272, 203, 3639, 279, 836, 18, 266, 10239, 12, 8949, 774, 426, 10239, 1769, 203, 203, 3639, 2254, 5034, 3844, 774, 1190, 9446, 273, 389, 8949, 397, 389, 1484, 81, 5077, 31, 203, 3639, 279, 836, 18, 1918, 9446, 12, 8949, 774, 1190, 9446, 1769, 203, 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 ]
./partial_match/4/0xb780d3599f40B15F58A422b835789C8B7b6eB8DD/sources/RecoverToken.sol
/Enable/Disable Safe Staking
bool private safestakingenabled;
8,764,601
[ 1, 19, 8317, 19, 11879, 14060, 934, 6159, 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, 1426, 3238, 11029, 395, 6159, 5745, 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 ]
// 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/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 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: @openzeppelin/contracts/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); } // File: @openzeppelin/contracts/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/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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/Rainbows.sol pragma solidity ^0.8.0; interface InterfaceNoundles { function noundleBalance(address owner) external view returns(uint256); } contract Rainbows is ERC20, Ownable, Pausable { InterfaceNoundles public Noundles; // The starting block. uint256 public startBlock; // The interval that the user is paid out. uint256 public interval = 86400; uint256 public rate = 4 ether; address public ticketContract; // The rewards for the user. mapping(address => uint256) public rewards; // The last time they were paid out. mapping(address => uint256) public lastUpdate; // Only allow the contract to interact with it. modifier onlyFromNoundles() { require(msg.sender == address(Noundles)); _; } constructor(address noundlesAddress) ERC20("NoundlesRainbows", "Rainbows") { // Set who the evofoxes address. Noundles = InterfaceNoundles(noundlesAddress); // Set the starting block. startBlock = block.timestamp; // Set to the owner for now. ticketContract = msg.sender; // Pause the system so no one can interact with it. _pause(); } /* Admin Utility. */ // Pause it. function pause() public onlyOwner { _pause(); } // Unpause it. function unpause() public onlyOwner { _unpause(); } // Set the start block. function setStartBlock(uint256 arg) public onlyOwner { if(arg == 0){ startBlock = block.timestamp; }else{ startBlock = arg; } } // Set the start block. function setIntervalAndRate(uint256 _interval, uint256 _rate) public onlyOwner { interval = _interval; rate = _rate; } // Set the address for the contract. function setNoundlesContractAddress(address _noundles) public onlyOwner { Noundles = InterfaceNoundles(_noundles); } // Set the address for the contract. function setTicketContractAddress(address _noundles) public onlyOwner { ticketContract = _noundles; } // Burn the tokens required to evolve. function burn(address user, uint256 amount) external { require(msg.sender == address(ticketContract), "Your address does not have permission to use burn"); _burn(user, amount); } /* User Utilities. */ // Transfer the tokens (only accessable from the contract). function transferTokens(address _from, address _to) onlyFromNoundles whenNotPaused external { if(_from != address(0)){ rewards[_from] += getPendingReward(_from); lastUpdate[_from] = block.timestamp; } if(_to != address(0)){ rewards[_to] += getPendingReward(_to); lastUpdate[_to] = block.timestamp; } } // Pay out the holder. function claimReward() external whenNotPaused { // Mint the user their tokens. _mint(msg.sender, rewards[msg.sender] + getPendingReward(msg.sender)); // Reset the rewards for the user. rewards[msg.sender] = 0; lastUpdate[msg.sender] = block.timestamp; } // The rewards to the user. function getTotalClaimable(address user) external view returns(uint256) { return rewards[user] + getPendingReward(user); } // The rewards to the user. function getlastUpdate(address user) external view returns(uint256) { return lastUpdate[user]; } // Get the total rewards. function getPendingReward(address user) internal view returns(uint256) { return Noundles.noundleBalance(user) * rate * (block.timestamp - (lastUpdate[user] >= startBlock ? lastUpdate[user] : startBlock)) / interval; } }
Set who the evofoxes address. Set the starting block. Set to the owner for now. Pause the system so no one can interact with it.
constructor(address noundlesAddress) ERC20("NoundlesRainbows", "Rainbows") { Noundles = InterfaceNoundles(noundlesAddress); startBlock = block.timestamp; ticketContract = msg.sender; _pause(); }
11,947,326
[ 1, 694, 10354, 326, 2113, 83, 13873, 281, 1758, 18, 1000, 326, 5023, 1203, 18, 1000, 358, 326, 3410, 364, 2037, 18, 31357, 326, 2619, 1427, 1158, 1245, 848, 16592, 598, 518, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3885, 12, 2867, 290, 772, 1040, 1887, 13, 4232, 39, 3462, 2932, 50, 772, 1040, 54, 530, 70, 543, 87, 3113, 315, 54, 530, 70, 543, 87, 7923, 288, 203, 203, 3639, 423, 772, 1040, 273, 6682, 50, 772, 1040, 12, 82, 772, 1040, 1887, 1769, 203, 203, 3639, 787, 1768, 273, 1203, 18, 5508, 31, 203, 203, 3639, 9322, 8924, 273, 1234, 18, 15330, 31, 203, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 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 ]
// Contract SKTL // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; contract SKTL is ERC20, Ownable, ERC20Permit, ERC20Votes, ERC20Pausable, ERC20Capped { uint256 public constant scaling = 10**36; // make sure totalRewardToken * scaling is still less than 2^256 // 3B fixed, to calculate the weight to payout rewards, set the accomodate the future max tokens uint256 public constant totalRewardToken = 3000 * 10**6 * 10**18; uint256 private _scaledRewardPerRewardToken; mapping(address => uint256) private _scaledRewardCreditedTo; mapping(address => uint256) private _rewardTokenBalance; uint256 private _scaledRemainder = 0; bool private _transferHookEnabled = true; constructor() ERC20("Skytale", "SKTL") ERC20Capped(300000000000000000000000000) // 300MM max ERC20Permit("Skytale") { require( owner() == _msgSender(), "owner is not the same as _msgSender()" ); // owner() will own the unclaimed tokens _mint(owner(), 200000000000000000000000000); // initial 200MM supply _rewardTokenBalance[owner()] = totalRewardToken; } function rewardBalance(address account) public view virtual returns (uint256) { uint256 scaledOwed = _scaledRewardPerRewardToken - _scaledRewardCreditedTo[account]; return (_rewardTokenBalance[account] * scaledOwed) / scaling; } function _update(address account) internal { uint256 owed = rewardBalance(account); if (owed > 0) { _transferHookEnabled = false; _transfer(owner(), account, owed); _transferHookEnabled = true; } _scaledRewardCreditedTo[account] = _scaledRewardPerRewardToken; } function transferOwnership(address newOwner) public virtual override onlyOwner { _update(newOwner); require( balanceOf(newOwner) == 0, "newOwner is required to hold no tokens" ); _update(owner()); // make sure transfer full balance of owner() _transferHookEnabled = false; _transfer(owner(), newOwner, balanceOf(owner())); _transferHookEnabled = true; _rewardTokenBalance[newOwner] = _rewardTokenBalance[owner()]; _rewardTokenBalance[owner()] = 0; _scaledRewardCreditedTo[newOwner] = _scaledRewardPerRewardToken; super.transferOwnership(newOwner); } function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, value); // this will call ERC20._beforeTokenTransfer if (!_transferHookEnabled) return; if (from == address(0)) // minting return; _update(from); _update(to); } function _afterTokenTransfer( address from, address to, uint256 value ) internal virtual override(ERC20, ERC20Votes) { super._afterTokenTransfer(from, to, value); if (!_transferHookEnabled) return; if (from == address(0)) // minting return; uint256 rewardTokenTransfered = (value * totalRewardToken) / totalSupply(); _rewardTokenBalance[from] -= rewardTokenTransfered; _rewardTokenBalance[to] += rewardTokenTransfered; } function increaseReward(uint256 amount) public onlyOwner { _mint(owner(), amount); // scale the deposit and add the previous remainder uint256 scaledAvailable = (amount * scaling) + _scaledRemainder; _scaledRewardPerRewardToken += scaledAvailable / totalRewardToken; _scaledRemainder = scaledAvailable % totalRewardToken; _scaledRewardCreditedTo[owner()] = _scaledRewardPerRewardToken; } function withdraw() public { require(rewardBalance(_msgSender()) > 0, "No rewards left to withdraw"); _update(_msgSender()); } function rewardTokenBalance(address addr) public view virtual returns (uint256) { return _rewardTokenBalance[addr]; } function _mint(address account, uint256 amount) internal virtual override(ERC20, ERC20Capped, ERC20Votes) { super._mint(account, amount); } function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) { super._burn(account, amount); } function pause() public onlyOwner { super._pause(); } function unpause() public onlyOwner { super._unpause(); } }
this will call ERC20._beforeTokenTransfer
super._beforeTokenTransfer(from, to, value);
12,739,435
[ 1, 2211, 903, 745, 4232, 39, 3462, 6315, 5771, 1345, 5912, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 460, 1769, 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 ]
./partial_match/4/0x0E69BcCfBC7D80457A6a7A6F12e0279bc964c518/sources/OneSplitAudit.sol
@notice Swap `amount` of `fromToken` to `destToken` @param fromToken (IERC20) Address of token or `address(0)` for Ether @param destToken (IERC20) Address of token or `address(0)` for Ether @param amount (uint256) Amount for `fromToken` @param minReturn (uint256) Minimum expected return, else revert @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn` @param flags (uint256) Flags for enabling and disabling some features, default 0
function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, ) public payable returns(uint256) { return swapWithReferral( fromToken, destToken, amount, minReturn, distribution, flags, address(0), 0 ); }
8,591,287
[ 1, 12521, 1375, 8949, 68, 434, 1375, 2080, 1345, 68, 358, 1375, 10488, 1345, 68, 225, 628, 1345, 261, 45, 654, 39, 3462, 13, 5267, 434, 1147, 578, 1375, 2867, 12, 20, 22025, 364, 512, 1136, 225, 1570, 1345, 261, 45, 654, 39, 3462, 13, 5267, 434, 1147, 578, 1375, 2867, 12, 20, 22025, 364, 512, 1136, 225, 3844, 261, 11890, 5034, 13, 16811, 364, 1375, 2080, 1345, 68, 225, 1131, 990, 261, 11890, 5034, 13, 23456, 2665, 327, 16, 469, 15226, 225, 7006, 261, 11890, 5034, 63, 5717, 1510, 434, 5376, 364, 3940, 7006, 2106, 635, 1375, 588, 6861, 990, 68, 225, 2943, 261, 11890, 5034, 13, 10104, 364, 570, 17912, 471, 1015, 17912, 2690, 4467, 16, 805, 374, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7720, 12, 203, 3639, 467, 654, 39, 3462, 628, 1345, 16, 203, 3639, 467, 654, 39, 3462, 1570, 1345, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 1131, 990, 16, 203, 3639, 2254, 5034, 8526, 3778, 7006, 16, 203, 565, 262, 1071, 8843, 429, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 7720, 1190, 1957, 29084, 12, 203, 5411, 628, 1345, 16, 203, 5411, 1570, 1345, 16, 203, 5411, 3844, 16, 203, 5411, 1131, 990, 16, 203, 5411, 7006, 16, 203, 5411, 2943, 16, 203, 5411, 1758, 12, 20, 3631, 203, 5411, 374, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.6; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "../utils/AuthorizableU.sol"; import "../token/XJoyToken.sol"; contract JoyPresale is ContextUpgradeable, AuthorizableU { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// // Info of each coin like USDT, USDC struct CoinInfo { address addr; uint256 rate; } // Info of each Vesting struct VestingInfo { uint8 initClaimablePercent; // Init Claimable Percent uint256 lockingDuration; // Locking Duration uint256 vestingDuration; // Vesting Duration } // Info of each Purchaser struct UserInfo { uint8 vestingIndex; // Index of VestingInfo uint256 depositedAmount; // How many Coins amount the user has deposited. uint256 purchasedAmount; // How many JOY tokens the user has purchased. uint256 withdrawnAmount; // Withdrawn amount uint256 firstDepositedTime; // Last Deposited time uint256 lastWithdrawnTime; // Last Withdrawn time } // The JOY Token IERC20Upgradeable public govToken; // The xJOY Token IERC20Upgradeable public xGovToken; // treasury addresses address[] public treasuryAddrs; uint16 public treasuryIndex; // Coin Info list CoinInfo[] public coinList; uint8 public COIN_DECIMALS; // Vesting Info VestingInfo[] public vestingList; // 0: Seed, 1: Presale A uint8 public VESTING_INDEX; // Sale flag and time. bool public SALE_FLAG; uint256 public SALE_START; uint256 public SALE_DURATION; // GovToken public flag bool public GOVTOKEN_PUBLIC_FLAG; // User address => UserInfo mapping(address => UserInfo) public userList; address[] public userAddrs; // total tokens amounts (all 18 decimals) uint256 public totalSaleAmount; uint256 public totalSoldAmount; uint256 public totalCoinAmount; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// // Events. event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount); event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount); // Modifiers. modifier whenSale() { require(checkSalePeriod(), "This is not sale period."); _; } modifier whenVesting(address userAddr) { require(checkVestingPeriod(userAddr), "This is not vesting period."); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken, uint256 _totalSaleAmount, CoinInfo[] memory _coinList, VestingInfo[] memory _vestingList ) public virtual initializer { __Context_init(); __Authorizable_init(); addAuthorized(_msgSender()); govToken = _govToken; xGovToken = _xGovToken; treasuryAddrs.push(_msgSender()); treasuryIndex = 0; COIN_DECIMALS = 18; setCoinList(_coinList); setVestingList(_vestingList); VESTING_INDEX = 0; startSale(false); updateSaleDuration(60 days); setGovTokenPublicFlag(false); updateTotalSaleAmount(_totalSaleAmount); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// // Update token function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized { govToken = _govToken; xGovToken = _xGovToken; } // Update the treasury address function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyAuthorized { delete treasuryAddrs; for (uint i=0; i<_treasuryAddrs.length; i++) { treasuryAddrs.push(_treasuryAddrs[i]); } treasuryIndex = 0; } function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized { treasuryIndex = _treasuryIndex; if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) { treasuryIndex = 0; } } // Set coin list function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized { delete coinList; for (uint i=0; i<_coinList.length; i++) { coinList.push(_coinList[i]); } } // Update coin info function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized { coinList[index] = CoinInfo(addr, rate); } // Set vesting list function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized { delete vestingList; for (uint i=0; i<_vestingList.length; i++) { vestingList.push(_vestingList[i]); } } function setVestingIndex(uint8 index) public onlyAuthorized { VESTING_INDEX = index; } // Update vesting info function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized { vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration); } // Start stop sale function startSale(bool bStart) public onlyAuthorized { SALE_FLAG = bStart; if (bStart) { SALE_START = block.timestamp; } } // Set GovToken public flag function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized { GOVTOKEN_PUBLIC_FLAG = bFlag; } // Update sale duration function updateSaleDuration(uint256 saleDuration) public onlyAuthorized { SALE_DURATION = saleDuration; } // check sale period function checkSalePeriod() public view returns (bool) { return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION); } // check locking period function checkLockingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration); return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); } // check vesting period function checkVestingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); // return block.timestamp >= VESTING_START; uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START; } // Update total sale amount function updateTotalSaleAmount(uint256 amount) public onlyAuthorized { totalSaleAmount = amount; } // Get user addrs function getUserAddrs() public view returns (address[] memory) { address[] memory returnData = new address[](userAddrs.length); for (uint i=0; i<userAddrs.length; i++) { returnData[i] = userAddrs[i]; } return returnData; } // Get user's vesting info function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex]; return vestingInfo; } // Set User Info function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized { UserInfo storage userInfo = userList[_addr]; if (userInfo.depositedAmount == 0) { userAddrs.push(_addr); userInfo.vestingIndex = _vestingIndex; userInfo.firstDepositedTime = block.timestamp; userInfo.depositedAmount = 0; userInfo.purchasedAmount = 0; userInfo.withdrawnAmount = 0; } else { totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount)); totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount)); } totalCoinAmount = totalCoinAmount.add(_depositedAmount); totalSoldAmount = totalSoldAmount.add(_purchasedAmount); userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount); userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_addr); } // Seed User List function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUser(address _userAddr, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner { setUserInfo(_userAddr, VESTING_INDEX, _depositedAmount, _purchasedAmount, 0); if (_transferToken) { xGovToken.safeTransfer(_userAddr, _purchasedAmount); } } // Deposit // coinAmount (decimals: COIN_DECIMALS) function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); // calculate token amount to be transferred (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); // if the token amount is less than remaining if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } // validate purchasing _preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex); // transfer coin and token coin.safeTransferFrom(_msgSender(), address(this), coinAmount); xGovToken.safeTransfer(_msgSender(), tokenAmount); // transfer coin to treasury if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } // update global state totalCoinAmount = totalCoinAmount.add(_coinAmount); totalSoldAmount = totalSoldAmount.add(tokenAmount); // update purchased token list UserInfo storage userInfo = userList[_msgSender()]; if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = VESTING_INDEX; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } // Withdraw function withdraw() external whenVesting(_msgSender()) { uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender()); uint256 govTokenAmount = govToken.balanceOf(address(this)); uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender())); uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount)); require(withdrawAmount > 0, "No withdraw amount!"); require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!"); xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount); govToken.safeTransfer(_msgSender(), withdrawAmount); UserInfo storage userInfo = userList[_msgSender()]; userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount); userInfo.lastWithdrawnTime = block.timestamp; emit TokensWithdrawed(_msgSender(), withdrawAmount); } // Calc token amount by coin amount function calcWithdrawalAmount(address userAddr) public view returns (uint256) { require(checkVestingPeriod(userAddr), "This is not vesting period."); UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); // uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); uint256 totalAmount = 0; if (block.timestamp <= VESTING_START) { totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100); } else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) { totalAmount = userInfo.purchasedAmount; } else { totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration); } uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount); return withdrawalAmount; } // Calc token amount by coin amount function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 tokenAmount = _coinAmount .mul(10**tokenDecimal) .div(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (tokenAmount, coinAmount); } // Calc coin amount by token amount function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 _coinAmount = _tokenAmount .div(10**_coinDecimal) .mul(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (_coinAmount, coinAmount); } // Calc max coin amount to be deposit function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) { uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); (uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex); return _coinAmount; } // Withdraw all coins by owner function withdrawAllCoins(address treasury) public onlyOwner { for (uint i=0; i<coinList.length; i++) { CoinInfo memory coinInfo = coinList[i]; IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr); uint256 coinAmount = _coin.balanceOf(address(this)); _coin.safeTransfer(treasury, coinAmount); } } // Withdraw all xJOY by owner function withdrawAllxGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = xGovToken.balanceOf(address(this)); xGovToken.safeTransfer(treasury, tokenAmount); } // Withdraw all $JOY by owner function withdrawAllGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = govToken.balanceOf(address(this)); govToken.safeTransfer(treasury, tokenAmount); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// // Validate purchase function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); require(purchaser != address(0), "Purchaser is the zero address"); require(coinAmount != 0, "Coin amount is 0"); require(tokenAmount != 0, "Token amount is 0"); require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!"); require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!"); require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!"); this; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library 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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract AuthorizableU is OwnableUpgradeable { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// mapping(address => bool) public isAuthorized; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event AddedAuthorized(address _user); event RemovedAuthorized(address _user); modifier onlyAuthorized() { require(isAuthorized[msg.sender] || owner() == msg.sender, "caller is not authorized"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __Authorizable_init() internal virtual initializer { __Ownable_init(); } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function addAuthorized(address _toAdd) public onlyOwner { isAuthorized[_toAdd] = true; emit AddedAuthorized(_toAdd); } function removeAuthorized(address _toRemove) public onlyOwner { require(_toRemove != msg.sender); isAuthorized[_toRemove] = false; emit RemovedAuthorized(_toRemove); } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./BlackListToken.sol"; contract XJoyToken is BlackListToken { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// uint256 public manualMinted; //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function initialize( string memory name, string memory symbol, uint256 initialSupply ) public virtual initializer { __ERC20_init(name, symbol); __BlackList_init(); _mint(_msgSender(), initialSupply); addAuthorized(_msgSender()); manualMinted = 0; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function manualMint(address _to, uint256 _amount) public onlyAuthorized { _mint(_to, _amount); manualMinted = manualMinted.add(_amount); } // add purchaser function addPurchaser(address addr) public onlyAuthorized { addBlackList(addr); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../utils/AuthorizableU.sol"; contract BlackListToken is ERC20Upgradeable, AuthorizableU { //////////////////////////////////////////////////////////////////////// // State variables //////////////////////////////////////////////////////////////////////// bool public isBlackListChecking; mapping (address => bool) public isBlackListed; // for from address mapping (address => bool) public isWhiteListed; // for to address //////////////////////////////////////////////////////////////////////// // Events & Modifiers //////////////////////////////////////////////////////////////////////// event SetBlackList(address[] _users, bool _status); event AddedBlackList(address _user); event RemovedBlackList(address _user); event SetWhiteList(address[] _users, bool _status); event AddedWhiteList(address _user); event RemovedWhiteList(address _user); modifier whenTransferable(address _from, address _to) { require(isTransferable(_from, _to), "[email protected]: transfer isn't allowed"); _; } //////////////////////////////////////////////////////////////////////// // Initialization functions //////////////////////////////////////////////////////////////////////// function __BlackList_init() internal virtual initializer { __Authorizable_init(); isBlackListChecking = true; } //////////////////////////////////////////////////////////////////////// // External functions //////////////////////////////////////////////////////////////////////// function startBlackList(bool _status) public onlyAuthorized { isBlackListChecking = _status; } // Blacklist function setBlackList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isBlackListed[_addrs[i]] = _status; } emit SetBlackList(_addrs, _status); } function addBlackList(address _toAdd) public onlyAuthorized { isBlackListed[_toAdd] = true; emit AddedBlackList(_toAdd); } function removeBlackList(address _toRemove) public onlyAuthorized { isBlackListed[_toRemove] = false; emit RemovedBlackList(_toRemove); } // Whitelist function setWhiteList(address[] memory _addrs, bool _status) public onlyAuthorized { for (uint256 i; i < _addrs.length; ++i) { isWhiteListed[_addrs[i]] = _status; } emit SetWhiteList(_addrs, _status); } function addWhiteList(address _toAdd) public onlyAuthorized { isWhiteListed[_toAdd] = true; emit AddedWhiteList(_toAdd); } function removeWhiteList (address _toRemove) public onlyAuthorized { isWhiteListed[_toRemove] = false; emit RemovedWhiteList(_toRemove); } function isTransferable(address _from, address _to) public view returns (bool) { if (isBlackListChecking) { // require(!isBlackListed[_from], "[email protected]: _from is in isBlackListed"); // require(!isBlackListed[_to] || isWhiteListed[_to], "[email protected]: _to is in isBlackListed"); require(!isBlackListed[_from] || isWhiteListed[_to], "[email protected]: _from is in isBlackListed"); } return true; } //////////////////////////////////////////////////////////////////////// // Internal functions //////////////////////////////////////////////////////////////////////// function _transfer(address _from, address _to, uint256 _amount) internal virtual override whenTransferable(_from, _to) { super._transfer(_from, _to, _amount); } }
State variables Info of each coin like USDT, USDC
contract JoyPresale is ContextUpgradeable, AuthorizableU { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; pragma solidity 0.8.6; struct CoinInfo { address addr; uint256 rate; } struct VestingInfo { } struct UserInfo { } uint16 public treasuryIndex; uint8 public COIN_DECIMALS; uint256 public SALE_START; uint256 public SALE_DURATION; address[] public userAddrs; uint256 public totalSoldAmount; uint256 public totalCoinAmount; event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount); IERC20Upgradeable public govToken; IERC20Upgradeable public xGovToken; address[] public treasuryAddrs; CoinInfo[] public coinList; uint8 public VESTING_INDEX; bool public SALE_FLAG; bool public GOVTOKEN_PUBLIC_FLAG; mapping(address => UserInfo) public userList; uint256 public totalSaleAmount; event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount); modifier whenSale() { require(checkSalePeriod(), "This is not sale period."); _; } modifier whenVesting(address userAddr) { require(checkVestingPeriod(userAddr), "This is not vesting period."); _; } function initialize( IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken, uint256 _totalSaleAmount, CoinInfo[] memory _coinList, VestingInfo[] memory _vestingList ) public virtual initializer { __Context_init(); __Authorizable_init(); addAuthorized(_msgSender()); govToken = _govToken; xGovToken = _xGovToken; treasuryAddrs.push(_msgSender()); treasuryIndex = 0; COIN_DECIMALS = 18; setCoinList(_coinList); setVestingList(_vestingList); VESTING_INDEX = 0; startSale(false); updateSaleDuration(60 days); setGovTokenPublicFlag(false); updateTotalSaleAmount(_totalSaleAmount); } function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized { govToken = _govToken; xGovToken = _xGovToken; } function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyAuthorized { delete treasuryAddrs; for (uint i=0; i<_treasuryAddrs.length; i++) { treasuryAddrs.push(_treasuryAddrs[i]); } treasuryIndex = 0; } function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyAuthorized { delete treasuryAddrs; for (uint i=0; i<_treasuryAddrs.length; i++) { treasuryAddrs.push(_treasuryAddrs[i]); } treasuryIndex = 0; } function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized { treasuryIndex = _treasuryIndex; if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) { treasuryIndex = 0; } } function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized { treasuryIndex = _treasuryIndex; if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) { treasuryIndex = 0; } } function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized { delete coinList; for (uint i=0; i<_coinList.length; i++) { coinList.push(_coinList[i]); } } function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized { delete coinList; for (uint i=0; i<_coinList.length; i++) { coinList.push(_coinList[i]); } } function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized { coinList[index] = CoinInfo(addr, rate); } function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized { delete vestingList; for (uint i=0; i<_vestingList.length; i++) { vestingList.push(_vestingList[i]); } } function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized { delete vestingList; for (uint i=0; i<_vestingList.length; i++) { vestingList.push(_vestingList[i]); } } function setVestingIndex(uint8 index) public onlyAuthorized { VESTING_INDEX = index; } function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized { vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration); } function startSale(bool bStart) public onlyAuthorized { SALE_FLAG = bStart; if (bStart) { SALE_START = block.timestamp; } } function startSale(bool bStart) public onlyAuthorized { SALE_FLAG = bStart; if (bStart) { SALE_START = block.timestamp; } } function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized { GOVTOKEN_PUBLIC_FLAG = bFlag; } function updateSaleDuration(uint256 saleDuration) public onlyAuthorized { SALE_DURATION = saleDuration; } function checkSalePeriod() public view returns (bool) { return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION); } function checkLockingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); } function checkVestingPeriod(address userAddr) public view returns (bool) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START; } function updateTotalSaleAmount(uint256 amount) public onlyAuthorized { totalSaleAmount = amount; } function getUserAddrs() public view returns (address[] memory) { address[] memory returnData = new address[](userAddrs.length); for (uint i=0; i<userAddrs.length; i++) { returnData[i] = userAddrs[i]; } return returnData; } function getUserAddrs() public view returns (address[] memory) { address[] memory returnData = new address[](userAddrs.length); for (uint i=0; i<userAddrs.length; i++) { returnData[i] = userAddrs[i]; } return returnData; } function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) { UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex]; return vestingInfo; } function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized { UserInfo storage userInfo = userList[_addr]; if (userInfo.depositedAmount == 0) { userAddrs.push(_addr); userInfo.vestingIndex = _vestingIndex; userInfo.firstDepositedTime = block.timestamp; userInfo.depositedAmount = 0; userInfo.purchasedAmount = 0; userInfo.withdrawnAmount = 0; totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount)); totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount)); } totalCoinAmount = totalCoinAmount.add(_depositedAmount); totalSoldAmount = totalSoldAmount.add(_purchasedAmount); userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount); userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_addr); } function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized { UserInfo storage userInfo = userList[_addr]; if (userInfo.depositedAmount == 0) { userAddrs.push(_addr); userInfo.vestingIndex = _vestingIndex; userInfo.firstDepositedTime = block.timestamp; userInfo.depositedAmount = 0; userInfo.purchasedAmount = 0; userInfo.withdrawnAmount = 0; totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount)); totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount)); } totalCoinAmount = totalCoinAmount.add(_depositedAmount); totalSoldAmount = totalSoldAmount.add(_purchasedAmount); userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount); userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_addr); } } else { function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner { for (uint i=0; i<_userAddrs.length; i++) { setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount); if (_transferToken) { xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount); } } } function seedUser(address _userAddr, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner { setUserInfo(_userAddr, VESTING_INDEX, _depositedAmount, _purchasedAmount, 0); if (_transferToken) { xGovToken.safeTransfer(_userAddr, _purchasedAmount); } } function seedUser(address _userAddr, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner { setUserInfo(_userAddr, VESTING_INDEX, _depositedAmount, _purchasedAmount, 0); if (_transferToken) { xGovToken.safeTransfer(_userAddr, _purchasedAmount); } } function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } xGovToken.safeTransfer(_msgSender(), tokenAmount); if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } totalSoldAmount = totalSoldAmount.add(tokenAmount); if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = VESTING_INDEX; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } xGovToken.safeTransfer(_msgSender(), tokenAmount); if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } totalSoldAmount = totalSoldAmount.add(tokenAmount); if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = VESTING_INDEX; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } _preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex); coin.safeTransferFrom(_msgSender(), address(this), coinAmount); function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } xGovToken.safeTransfer(_msgSender(), tokenAmount); if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } totalSoldAmount = totalSoldAmount.add(tokenAmount); if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = VESTING_INDEX; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } totalCoinAmount = totalCoinAmount.add(_coinAmount); UserInfo storage userInfo = userList[_msgSender()]; function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale { require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex); uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); if (availableTokenAmount < tokenAmount) { tokenAmount = availableTokenAmount; (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex); } xGovToken.safeTransfer(_msgSender(), tokenAmount); if (treasuryAddrs.length != 0) { coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount); } totalSoldAmount = totalSoldAmount.add(tokenAmount); if (userInfo.depositedAmount == 0) { userAddrs.push(_msgSender()); userInfo.vestingIndex = VESTING_INDEX; userInfo.firstDepositedTime = block.timestamp; } userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount); userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount); emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount); XJoyToken _xJoyToken = XJoyToken(address(xGovToken)); _xJoyToken.addPurchaser(_msgSender()); } function withdraw() external whenVesting(_msgSender()) { uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender()); uint256 govTokenAmount = govToken.balanceOf(address(this)); uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender())); uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount)); require(withdrawAmount > 0, "No withdraw amount!"); require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!"); xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount); govToken.safeTransfer(_msgSender(), withdrawAmount); UserInfo storage userInfo = userList[_msgSender()]; userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount); userInfo.lastWithdrawnTime = block.timestamp; emit TokensWithdrawed(_msgSender(), withdrawAmount); } function calcWithdrawalAmount(address userAddr) public view returns (uint256) { require(checkVestingPeriod(userAddr), "This is not vesting period."); UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); uint256 totalAmount = 0; if (block.timestamp <= VESTING_START) { totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100); totalAmount = userInfo.purchasedAmount; totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration); } uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount); return withdrawalAmount; } function calcWithdrawalAmount(address userAddr) public view returns (uint256) { require(checkVestingPeriod(userAddr), "This is not vesting period."); UserInfo memory userInfo = userList[userAddr]; VestingInfo memory vestingInfo = getUserVestingInfo(userAddr); uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration); uint256 totalAmount = 0; if (block.timestamp <= VESTING_START) { totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100); totalAmount = userInfo.purchasedAmount; totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration); } uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount); return withdrawalAmount; } } else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) { } else { function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 tokenAmount = _coinAmount .mul(10**tokenDecimal) .div(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (tokenAmount, coinAmount); } function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr); uint256 rate = coinInfo.rate; uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS; uint256 _coinAmount = _tokenAmount .div(10**_coinDecimal) .mul(rate); uint coinDecimal = COIN_DECIMALS - coin.decimals(); uint256 coinAmount = _coinAmount .div(10**coinDecimal); return (_coinAmount, coinAmount); } function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) { uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount); (uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex); return _coinAmount; } function withdrawAllCoins(address treasury) public onlyOwner { for (uint i=0; i<coinList.length; i++) { CoinInfo memory coinInfo = coinList[i]; IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr); uint256 coinAmount = _coin.balanceOf(address(this)); _coin.safeTransfer(treasury, coinAmount); } } function withdrawAllCoins(address treasury) public onlyOwner { for (uint i=0; i<coinList.length; i++) { CoinInfo memory coinInfo = coinList[i]; IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr); uint256 coinAmount = _coin.balanceOf(address(this)); _coin.safeTransfer(treasury, coinAmount); } } function withdrawAllxGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = xGovToken.balanceOf(address(this)); xGovToken.safeTransfer(treasury, tokenAmount); } function withdrawAllGovTokens(address treasury) public onlyOwner { uint256 tokenAmount = govToken.balanceOf(address(this)); govToken.safeTransfer(treasury, tokenAmount); } function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view { require( coinList.length > coinIndex, "coinList.length > coinIndex"); CoinInfo memory coinInfo = coinList[coinIndex]; IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr); require(purchaser != address(0), "Purchaser is the zero address"); require(coinAmount != 0, "Coin amount is 0"); require(tokenAmount != 0, "Token amount is 0"); require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!"); require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!"); require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!"); this; } }
12,088,018
[ 1, 1119, 3152, 3807, 434, 1517, 13170, 3007, 11836, 9081, 16, 11836, 5528, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 804, 13372, 12236, 5349, 353, 1772, 10784, 429, 16, 3123, 5331, 429, 57, 288, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 26, 31, 203, 565, 1958, 28932, 966, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 5034, 4993, 31, 203, 565, 289, 203, 203, 565, 1958, 776, 10100, 966, 288, 203, 565, 289, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 203, 565, 2254, 2313, 1071, 9787, 345, 22498, 1016, 31, 203, 203, 565, 2254, 28, 1071, 385, 6266, 67, 23816, 55, 31, 203, 203, 203, 565, 2254, 5034, 1071, 17127, 900, 67, 7570, 31, 203, 565, 2254, 5034, 1071, 17127, 900, 67, 24951, 31, 203, 203, 203, 565, 1758, 8526, 1071, 729, 13811, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 55, 1673, 6275, 31, 203, 565, 2254, 5034, 1071, 2078, 27055, 6275, 31, 7010, 203, 565, 871, 13899, 1190, 9446, 329, 12, 2867, 8808, 5405, 343, 14558, 16, 2254, 5034, 1147, 6275, 1769, 203, 203, 565, 467, 654, 39, 3462, 10784, 429, 1071, 31841, 1345, 31, 203, 565, 467, 654, 39, 3462, 10784, 429, 1071, 619, 43, 1527, 1345, 31, 203, 565, 1758, 8526, 1071, 9787, 345, 22498, 13811, 31, 203, 565, 28932, 966, 8526, 1071, 13170, 682, 31, 203, 565, 2254, 28, 1071, 776, 11027, 1360, 67, 9199, 31, 203, 565, 1426, 1071, 17127, 2 ]
pragma solidity >=0.4.4 <0.7.0; contract Modifier { //Ejemplo de solo propietario del contrato puede ejecutar una function address public owner; constructor() public { owner = msg.sender; } modifier soloPropietario(){ require(msg.sender == owner, "Notienes permisos para ejecutar la funcion"); _; } function ejemplo1() public soloPropietario(){ //Codigo de la funcion para el propietario del contrato } struct cliente { address direccion; string nombre; } mapping(string => address) clientes; function altaCliente(string memory _nombre) public { clientes[_nombre] = msg.sender; } modifier soloClientes(string memory _nombre){ require(clientes[_nombre] == msg.sender); _; } function ejemplo2(string memory _nombre) public soloClientes(_nombre) { //logica de la funcion para los clientes } //Ejemplo de conduccion modifier MayorEdad(uint _edadMinima, uint _edadUsuario){ require(_edadUsuario >= _edadMinima); _; } function conducir(uint _edad) public MayorEdad(18, _edad){ //Codigo a ejecutar para los conductores mayores de edad } }
Codigo a ejecutar para los conductores mayores de edad
function conducir(uint _edad) public MayorEdad(18, _edad){ }
12,703,699
[ 1, 29633, 17626, 279, 425, 78, 557, 322, 297, 12602, 22148, 356, 1828, 3485, 2026, 3485, 443, 1675, 361, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 356, 2544, 11614, 12, 11890, 389, 329, 361, 13, 1071, 16734, 280, 2671, 361, 12, 2643, 16, 389, 329, 361, 15329, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; import "./openzeppelin/Ownable.sol"; import "./snarklibs/SnarkBaseLib.sol"; import "./snarklibs/SnarkLoanLib.sol"; import "./openzeppelin/SafeMath.sol"; /// @title Contract creates the functionality to loan tokens /// @author Vitali Hurski contract SnarkLoan is Ownable { using SnarkBaseLib for address; using SnarkLoanLib for address; using SafeMath for uint256; address payable private _storage; address private _erc721; event LoanCreated(address indexed loanOwner, uint256 loanId); event LoanDeleted(uint256 loanId); modifier restrictedAccess() { if (SnarkBaseLib.isRestrictedAccess(_storage)) { require(msg.sender == owner, "only Snark can perform the function"); } _; } modifier correctLoan(uint256 loanId) { require( loanId > 0 && loanId <= SnarkLoanLib.getNumberOfLoans(_storage), "Loan id is wrong" ); _; } modifier onlyLoanOwner(uint256 loanId) { require( msg.sender == SnarkLoanLib.getOwnerOfLoan(_storage, loanId), "Only loan owner can borrow tokens" ); _; } modifier onlyLoanOwnerOrSnark(uint256 loanId) { require( msg.sender == SnarkLoanLib.getOwnerOfLoan(_storage, loanId) || msg.sender == owner, "Only loan owner and Snark can call this function" ); _; } /// @dev Contract Constructor /// @param storageAddress Address of a storage contract /// @param erc721Address Address of a ERC721 contract constructor(address payable storageAddress, address erc721Address) public { _storage = storageAddress; _erc721 = erc721Address; } /// @notice Will receive any eth sent to the contract function() external payable {} // solhint-disable-line /// @dev Function to destroy the contract on the blockchain function kill() external onlyOwner { selfdestruct(msg.sender); } function setDefaultLoanDuration(uint256 duration) public onlyOwner { SnarkLoanLib.setDefaultLoanDuration(_storage, duration); } function getDefaultLoanDuration() public view returns (uint256) { return SnarkLoanLib.getDefaultLoanDuration(_storage); } function getLoanDetail(uint256 loanId) public view returns (address, uint256, uint256, uint256, uint256, uint256) { return ( SnarkLoanLib.getOwnerOfLoan(_storage, loanId), SnarkLoanLib.getLoanStartDate(_storage, loanId), SnarkLoanLib.getLoanEndDate(_storage, loanId), SnarkLoanLib.getPreviousLoan(_storage, loanId), SnarkLoanLib.getNextLoan(_storage, loanId), SnarkLoanLib.getLoanPrice(_storage, loanId) ); } /// @dev Attributes of timestamp_start and timestamp_end should contain 10 digits only /// @param timestampStart Contains date and time of loan start /// @param timestampEnd Contain date and time of loan end function createLoan(uint256 timestampStart, uint256 timestampEnd) public payable restrictedAccess { require(SnarkBaseLib.getOwnedTokensCount(_storage, msg.sender) > 0, "User has to have at least one token"); require(timestampStart > block.timestamp, "Start of loan less than current time"); // solhint-disable-line require(timestampEnd > timestampStart, "Datetime of a loan end has to be bigger the datetime of start one."); uint256 duration = (timestampEnd - timestampStart); require(duration <= getDefaultLoanDuration().mul(86400), "Duration exceeds a max value"); SnarkLoanLib.toShiftPointer(_storage); uint256 afterLoanId; uint256 beforeLoanId; bool isCrossedPeriod; (afterLoanId, beforeLoanId, isCrossedPeriod) = SnarkLoanLib.findPosition(_storage, timestampStart, timestampEnd); require(!isCrossedPeriod, "Selected period has not to crossed with existing loans"); // Add loan and set pointer uint256 loanId = SnarkLoanLib.increaseMaxLoanId(_storage); SnarkLoanLib.setOwnerOfLoan(_storage, loanId, msg.sender); SnarkLoanLib.setLoanStartDate(_storage, loanId, timestampStart); SnarkLoanLib.setLoanEndDate(_storage, loanId, timestampEnd); SnarkLoanLib.setNextLoan(_storage, loanId, beforeLoanId); SnarkLoanLib.setPreviousLoan(_storage, loanId, afterLoanId); SnarkLoanLib.setLoanPrice(_storage, loanId, msg.value); // Keep the ether in the storage contract if (msg.value > 0) _storage.transfer(msg.value); // Update number of loans SnarkLoanLib.setNumberOfLoans(_storage, SnarkLoanLib.getNumberOfLoans(_storage).add(1)); // Add loan to the owner list SnarkLoanLib.addLoanToOwnerList(_storage, msg.sender, loanId); if (afterLoanId == 0) { SnarkLoanLib.setLoanPointer(_storage, loanId); } else { SnarkLoanLib.setNextLoan(_storage, afterLoanId, loanId); } if (beforeLoanId == 0) { SnarkLoanLib.setTopBoundaryOfLoansPeriod(_storage, timestampEnd); } else { SnarkLoanLib.setPreviousLoan(_storage, beforeLoanId, loanId); } emit LoanCreated(msg.sender, loanId); } function deleteLoan(uint256 loanId) public onlyLoanOwnerOrSnark(loanId) { bool isDeleted = SnarkLoanLib.isLoanDeleted(_storage, loanId); require(isDeleted == false, "Loan does not exist"); uint256 beforeLoanId = SnarkLoanLib.getPreviousLoan(_storage, loanId); uint256 nextLoanId = SnarkLoanLib.getNextLoan(_storage, loanId); uint256 countOfLoans = SnarkLoanLib.getNumberOfLoans(_storage); if (beforeLoanId == 0 && nextLoanId == 0) { SnarkLoanLib.setLoanPointer(_storage, 0); SnarkLoanLib.setBottomBoundaryOfLoansPeriod(_storage, 0); SnarkLoanLib.setTopBoundaryOfLoansPeriod(_storage, 0); if (countOfLoans > 0) { SnarkLoanLib.setNumberOfLoans(_storage, countOfLoans.sub(1)); } } if (beforeLoanId == 0 && nextLoanId > 0) { SnarkLoanLib.setPreviousLoan(_storage, nextLoanId, 0); uint256 pointerToLoan = SnarkLoanLib.getLoanPointer(_storage); if (pointerToLoan == loanId) { SnarkLoanLib.setLoanPointer(_storage, nextLoanId); } uint256 bottomTime = SnarkLoanLib.getLoanStartDate(_storage, nextLoanId); SnarkLoanLib.setBottomBoundaryOfLoansPeriod(_storage, bottomTime); if (countOfLoans > 0) { SnarkLoanLib.setNumberOfLoans(_storage, countOfLoans.sub(1)); } } if (beforeLoanId > 0 && nextLoanId == 0) { SnarkLoanLib.setNextLoan(_storage, beforeLoanId, 0); uint256 topTime = SnarkLoanLib.getLoanEndDate(_storage, beforeLoanId); SnarkLoanLib.setTopBoundaryOfLoansPeriod(_storage, topTime); if (countOfLoans > 0) { SnarkLoanLib.setNumberOfLoans(_storage, countOfLoans.sub(1)); } } if (beforeLoanId > 0 && nextLoanId > 0) { SnarkLoanLib.setNextLoan(_storage, beforeLoanId, nextLoanId); SnarkLoanLib.setPreviousLoan(_storage, nextLoanId, beforeLoanId); if (countOfLoans > 0) { SnarkLoanLib.setNumberOfLoans(_storage, countOfLoans.sub(1)); } } // Remove loan from the owner list address loanOwner = SnarkLoanLib.getOwnerOfLoan(_storage, loanId); SnarkLoanLib.deleteLoanFromOwnerList(_storage, loanOwner, loanId); SnarkLoanLib.markLoanAsDeleted(_storage, loanId); toShiftPointer(); emit LoanDeleted(loanId); } function getNumberOfLoans() public view returns (uint256) { return SnarkLoanLib.getNumberOfLoans(_storage); } function getListOfLoans() public view returns (uint256[] memory) { uint256 numberOfLoans = getNumberOfLoans(); uint256[] memory loans = new uint256[](numberOfLoans); if (numberOfLoans > 0) { uint256 id = SnarkLoanLib.getLoanId(_storage); for (uint256 i = 0; i < numberOfLoans; i++) { loans[i] = id; id = SnarkLoanLib.getNextLoan(_storage, id); } } return loans; } function getListOfLoansOfOwner(address loanOwner) public view returns (uint256[] memory) { uint256 numberOfLoans = getCountOfOwnerLoans(loanOwner); uint256[] memory loansList = new uint256[](numberOfLoans); uint256 loanId; for (uint256 i = 0; i < numberOfLoans; i++) { loanId = SnarkLoanLib.getLoanFromOwnerListByIndex(_storage, loanOwner, i); if (!isLoanFinished(loanId)) { loansList[i] = loanId; } } return loansList; } function getCountOfOwnerLoans(address loanOwner) public view returns (uint256) { uint256 amountOfAllOwnerLoans = SnarkLoanLib.getTotalNumberOfLoansInOwnerList(_storage, loanOwner); uint256 amountOfActiveOwnerLoans; uint256 loanId; bool isActive; for (uint256 i = 0; i < amountOfAllOwnerLoans; i++) { loanId = SnarkLoanLib.getLoanFromOwnerListByIndex(_storage, loanOwner, i); isActive = isLoanFinished(loanId); if (!isActive) { amountOfActiveOwnerLoans++; } } return amountOfActiveOwnerLoans; } function getLoanId() public view returns (uint256) { return SnarkLoanLib.getLoanId(_storage); } function doUserHaveAccessToToken(address userWalletId, uint256 tokenId) public view returns (bool) { address realOwner = SnarkBaseLib.getOwnerOfToken(_storage, tokenId); bool isUserHasAccess = (userWalletId == realOwner); if (!isUserHasAccess) { uint256 loanId = SnarkLoanLib.getLoanId(_storage); if (SnarkLoanLib.isLoanActive(_storage, loanId)) { address loanOwner = SnarkLoanLib.getOwnerOfLoan(_storage, loanId); bool isApproved = SnarkLoanLib.isTokenInApprovedListForLoan(_storage, tokenId); isUserHasAccess = (loanOwner == userWalletId && isApproved); } } return isUserHasAccess; } function isLoanActive(uint256 loanId) public view returns (bool) { return SnarkLoanLib.isLoanActive(_storage, loanId); } function isLoanFinished(uint256 loanId) public view returns (bool) { return SnarkLoanLib.isLoanFinished(_storage, loanId); } function isLoanDeleted(uint256 loanId) public view returns (bool) { return SnarkLoanLib.isLoanDeleted(_storage, loanId); } function toShiftPointer() public { uint256 loanId = SnarkLoanLib.getLoanPointer(_storage); if (SnarkLoanLib.isLoanFinished(_storage, loanId) || SnarkLoanLib.isLoanDeleted(_storage, loanId)) { SnarkLoanLib.toShiftPointer(_storage); } } function getListOfBusyDates() public view returns(uint256[] memory, uint256[] memory) { uint256 loanId = getLoanId(); uint256 countOfLoans; while (loanId > 0) { countOfLoans++; loanId = SnarkLoanLib.getNextLoan(_storage, loanId); } uint256[] memory startBusyDate = new uint256[](countOfLoans); uint256[] memory endBusyDate = new uint256[](countOfLoans); uint256 startTimestamp; uint256 endTimestamp; uint256 index; loanId = getLoanId(); while (loanId > 0) { (, startTimestamp, endTimestamp, , ,) = getLoanDetail(loanId); startBusyDate[index] = startTimestamp; endBusyDate[index] = endTimestamp; loanId = SnarkLoanLib.getNextLoan(_storage, loanId); index = index.add(1); } return (startBusyDate, endBusyDate); } }
@dev Attributes of timestamp_start and timestamp_end should contain 10 digits only @param timestampStart Contains date and time of loan start @param timestampEnd Contain date and time of loan end Add loan and set pointer Keep the ether in the storage contract Update number of loans Add loan to the owner list
function createLoan(uint256 timestampStart, uint256 timestampEnd) public payable restrictedAccess { require(SnarkBaseLib.getOwnedTokensCount(_storage, msg.sender) > 0, "User has to have at least one token"); require(timestampEnd > timestampStart, "Datetime of a loan end has to be bigger the datetime of start one."); uint256 duration = (timestampEnd - timestampStart); require(duration <= getDefaultLoanDuration().mul(86400), "Duration exceeds a max value"); SnarkLoanLib.toShiftPointer(_storage); uint256 afterLoanId; uint256 beforeLoanId; bool isCrossedPeriod; (afterLoanId, beforeLoanId, isCrossedPeriod) = SnarkLoanLib.findPosition(_storage, timestampStart, timestampEnd); require(!isCrossedPeriod, "Selected period has not to crossed with existing loans"); uint256 loanId = SnarkLoanLib.increaseMaxLoanId(_storage); SnarkLoanLib.setOwnerOfLoan(_storage, loanId, msg.sender); SnarkLoanLib.setLoanStartDate(_storage, loanId, timestampStart); SnarkLoanLib.setLoanEndDate(_storage, loanId, timestampEnd); SnarkLoanLib.setNextLoan(_storage, loanId, beforeLoanId); SnarkLoanLib.setPreviousLoan(_storage, loanId, afterLoanId); SnarkLoanLib.setLoanPrice(_storage, loanId, msg.value); if (msg.value > 0) _storage.transfer(msg.value); SnarkLoanLib.setNumberOfLoans(_storage, SnarkLoanLib.getNumberOfLoans(_storage).add(1)); SnarkLoanLib.addLoanToOwnerList(_storage, msg.sender, loanId); if (afterLoanId == 0) { SnarkLoanLib.setLoanPointer(_storage, loanId); SnarkLoanLib.setNextLoan(_storage, afterLoanId, loanId); } if (beforeLoanId == 0) { SnarkLoanLib.setTopBoundaryOfLoansPeriod(_storage, timestampEnd); SnarkLoanLib.setPreviousLoan(_storage, beforeLoanId, loanId); } emit LoanCreated(msg.sender, loanId); }
14,069,935
[ 1, 2498, 434, 2858, 67, 1937, 471, 2858, 67, 409, 1410, 912, 1728, 6815, 1338, 225, 2858, 1685, 8398, 1509, 471, 813, 434, 28183, 787, 225, 2858, 1638, 1816, 530, 1509, 471, 813, 434, 28183, 679, 1436, 28183, 471, 444, 4407, 10498, 326, 225, 2437, 316, 326, 2502, 6835, 2315, 1300, 434, 437, 634, 1436, 28183, 358, 326, 3410, 666, 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, 752, 1504, 304, 12, 11890, 5034, 2858, 1685, 16, 2254, 5034, 2858, 1638, 13, 1071, 8843, 429, 15693, 1862, 288, 203, 3639, 2583, 12, 10461, 1313, 2171, 5664, 18, 588, 5460, 329, 5157, 1380, 24899, 5697, 16, 1234, 18, 15330, 13, 405, 374, 16, 315, 1299, 711, 358, 1240, 622, 4520, 1245, 1147, 8863, 203, 3639, 2583, 12, 5508, 1638, 405, 2858, 1685, 16, 315, 16103, 434, 279, 28183, 679, 711, 358, 506, 18983, 326, 3314, 434, 787, 1245, 1199, 1769, 203, 3639, 2254, 5034, 3734, 273, 261, 5508, 1638, 300, 2858, 1685, 1769, 203, 3639, 2583, 12, 8760, 1648, 4829, 1504, 304, 5326, 7675, 16411, 12, 28, 1105, 713, 3631, 315, 5326, 14399, 279, 943, 460, 8863, 203, 203, 3639, 18961, 1313, 1504, 304, 5664, 18, 869, 10544, 4926, 24899, 5697, 1769, 203, 203, 3639, 2254, 5034, 1839, 1504, 304, 548, 31, 203, 3639, 2254, 5034, 1865, 1504, 304, 548, 31, 203, 3639, 1426, 25249, 6973, 730, 5027, 31, 203, 3639, 261, 5205, 1504, 304, 548, 16, 1865, 1504, 304, 548, 16, 25249, 6973, 730, 5027, 13, 273, 7010, 5411, 18961, 1313, 1504, 304, 5664, 18, 4720, 2555, 24899, 5697, 16, 2858, 1685, 16, 2858, 1638, 1769, 203, 3639, 2583, 12, 5, 291, 39, 6973, 730, 5027, 16, 315, 7416, 3879, 711, 486, 358, 30783, 730, 598, 2062, 437, 634, 8863, 203, 203, 3639, 2254, 5034, 28183, 548, 273, 18961, 1313, 1504, 304, 5664, 18, 267, 11908, 2747, 1504, 304, 548, 24899, 5697, 1769, 203, 3639, 18961, 1313, 1504, 304, 5664, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0 <0.7.0; import "./AufToken.sol"; import "./AufNFT.sol"; contract AufFarming { string public name = "Farm AMONG NFT"; address public owner; AufToken public aufToken; AufNFT public aufNFT; address[] public stakers; mapping(address => uint) public stakingBalance; mapping(address => bool) public hasStaked; mapping(address => bool) public isStaking; constructor(AufToken _aufToken, AufNFT _aufNFT) public { aufToken = _aufToken; aufNFT = _aufNFT; owner = msg.sender; } function stakeTokens(uint _amount) public { require(_amount == 10000000000000000000000, "amount must be 10,000 AMONG"); // Trasnfer Auf tokens to this contract for staking aufToken.transferFrom(msg.sender, address(this), _amount); // Update staking balance stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; // Add user to stakers array *only* if they haven't staked already if(!hasStaked[msg.sender]) { stakers.push(msg.sender); } // Update staking status isStaking[msg.sender] = true; hasStaked[msg.sender] = true; } // Unstaking Tokens (Withdraw) function unstakeTokens() public { // Fetch staking balance uint balance = stakingBalance[msg.sender]; // Require amount greater than 0 require(balance > 0, "staking balance cannot be 0"); // Transfer Auf tokens to this contract for staking aufToken.transfer(msg.sender, balance); // Reset staking balance stakingBalance[msg.sender] = 0; // Update staking status isStaking[msg.sender] = false; } // Issuing Tokens function issueNFT() public { // Only owner can call this function require(msg.sender == owner, "caller must be the owner"); // Issue tokens to all stakers for (uint i=0; i<stakers.length; i++) { address recipient = stakers[i]; uint balance = stakingBalance[recipient]; uint NFTtokens = 0; if(balance > 0) { NFTtokens = balance / 10000000000000000000000; for (uint j=0; j<NFTtokens; j++) { aufNFT.mint(recipient); } } } } } pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./AufToken.sol"; contract AufNFT is Ownable, ERC721 { using SafeMath2 for uint; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(authorized[msg.sender] || owner() == msg.sender); _; } constructor() ERC721("Amongus.finance Ticket", "ATICKET") public { _setBaseURI("https://raw.githubusercontent.com/aufgames/aufcore/main/nftURI/id_"); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function addAuthorized(address _toAdd) onlyOwner public { require(_toAdd != address(0)); authorized[_toAdd] = true; } function removeAuthorized(address _toRemove) onlyOwner public { require(_toRemove != address(0)); require(_toRemove != msg.sender); authorized[_toRemove] = false; } function mint(address to) public onlyAuthorized { uint _tokenId = totalSupply().add(1); _mint(to, _tokenId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0 <0.7.0; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () public { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, _newOwner); _owner = _newOwner; } } library SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } interface ERC20{ function totalSupply() external view returns (uint256); function balanceOf(address _tokenOwner) external view returns (uint256); function allowance(address _tokenOwner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _tokens) external returns (bool); function approve(address _spender, uint256 _tokens) external returns (bool); function transferFrom(address _from, address _to, uint256 _tokens) external returns (bool); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); } contract AufToken is Ownable, ERC20{ using SafeMath for uint256; string _name; string _symbol; uint256 _totalSupply; uint256 _decimal; mapping(address => uint256) _balances; mapping(address => mapping (address => uint256)) _allowances; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); constructor() public { _name = "Amongus.finance"; _symbol = "AMONG"; _decimal = 18; _totalSupply = 21000000 * 10 ** _decimal; _balances[0xf2596513BccbCbF318d5A18AF9A8A24EA589D0C7] = _totalSupply; emit Transfer(address(0), 0xf2596513BccbCbF318d5A18AF9A8A24EA589D0C7, _totalSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint256) { return _decimal; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address _tokenOwner) external view override returns (uint256) { return _balances[_tokenOwner]; } function transfer(address _to, uint256 _tokens) external override returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function _transfer(address _sender, address _recipient, uint256 _amount) internal { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); _balances[_sender] = _balances[_sender].safeSub(_amount); _balances[_recipient] = _balances[_recipient].safeAdd(_amount); emit Transfer(_sender, _recipient, _amount); } function allowance(address _tokenOwner, address _spender) external view override returns (uint256) { return _allowances[_tokenOwner][_spender]; } function approve(address _spender, uint256 _tokens) external override returns (bool) { _approve(msg.sender, _spender, _tokens); return true; } function _approve(address _owner, address _spender, uint256 _value) internal { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); } function transferFrom(address _from, address _to, uint256 _tokens) external override returns (bool) { _transfer(_from, _to, _tokens); _approve(_from, msg.sender, _allowances[_from][msg.sender].safeSub(_tokens)); return true; } receive () external payable { revert(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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 SafeMath2 { /** * @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; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @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 SafeMath2 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json")); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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 = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev 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(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev 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(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Trasnfer Auf tokens to this contract for staking Update staking balance Add user to stakers array *only* if they haven't staked already
function stakeTokens(uint _amount) public { require(_amount == 10000000000000000000000, "amount must be 10,000 AMONG"); aufToken.transferFrom(msg.sender, address(this), _amount); stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; if(!hasStaked[msg.sender]) { stakers.push(msg.sender); } hasStaked[msg.sender] = true; }
5,830,676
[ 1, 1070, 31432, 586, 432, 696, 2430, 358, 333, 6835, 364, 384, 6159, 2315, 384, 6159, 11013, 1436, 729, 358, 384, 581, 414, 526, 1338, 309, 2898, 15032, 1404, 384, 9477, 1818, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 384, 911, 5157, 12, 11890, 389, 8949, 13, 1071, 288, 203, 3639, 203, 3639, 2583, 24899, 8949, 422, 2130, 12648, 12648, 2787, 16, 315, 8949, 1297, 506, 1728, 16, 3784, 20653, 7390, 8863, 203, 203, 3639, 279, 696, 1345, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 203, 3639, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 273, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 397, 389, 8949, 31, 203, 203, 3639, 309, 12, 5, 5332, 510, 9477, 63, 3576, 18, 15330, 5717, 288, 203, 5411, 384, 581, 414, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 203, 3639, 711, 510, 9477, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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; } } pragma solidity ^0.5.0; /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } pragma solidity ^0.5.0; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } pragma solidity ^0.5.0; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } pragma solidity ^0.5.0; /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // 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))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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)); } } pragma solidity ^0.5.0; /** * Валидаторы */ contract ValidationUtil { function requireNotEmptyAddress(address value) internal view{ require(isAddressNotEmpty(value)); } function isAddressNotEmpty(address value) internal view returns (bool result){ return value != address(0x0); } } pragma solidity ^0.5.0; /** * Контракт шахт */ contract ImpMine is Ownable, Pausable, ValidationUtil { using ECDSA for bytes32; /* Акк, куда переводятся средства */ address payable private _destinationWallet; /* Мапа уже совершенных апгрейдов, хэш: акк пользователя + id шахты + level */ mapping (bytes32 => bool) private _userUpgrades; /* Мапа стоимостей агрейда: level => wei */ mapping (uint => uint) private _upgradePrices; /* Событие апгрейда шахты */ event MineUpgraded(address receiver, uint mineId, uint level, uint buyPrice); function upgrade(uint mineId, uint level, bytes calldata signature) external payable validDestinationWallet whenNotPaused { // 0 суммы - не принимаем require(msg.value != 0); // Акк пользователя, id шахты, уровень апгрейда bytes32 validatingHash = keccak256(abi.encodePacked(msg.sender, mineId, level)); // Подписывать все транзакции должен owner address addressRecovered = validatingHash.toEthSignedMessageHash().recover(signature); require(addressRecovered == owner()); // Проверям, был ли уже апгрейд? require(!_userUpgrades[validatingHash]); //Проверяем установленную сумму в апгрейде require(_upgradePrices[level] == msg.value); // Делаем перевод получателю, в случае неудачи будет throws _destinationWallet.transfer(msg.value); _userUpgrades[validatingHash] = true; emit MineUpgraded(msg.sender, mineId, level, msg.value); } function isUserUpgraded(address userAddress, uint mineId, uint level) public view returns (bool) { return _userUpgrades[keccak256(abi.encodePacked(userAddress, mineId, level))]; } function setUpgradePrice(uint level, uint price) external onlyOwner { // 0 суммы - не принимаем require(price != 0); _upgradePrices[level] = price; } function getUpgradePrice(uint level) public view returns (uint) { return _upgradePrices[level]; } function setDestinationWallet(address payable walletAddress) external onlyOwner { requireNotEmptyAddress(walletAddress); _destinationWallet = walletAddress; } function getDestinationWallet() public view returns (address) { return _destinationWallet; } modifier validDestinationWallet() { requireNotEmptyAddress(_destinationWallet); _; } }
0 суммы - не принимаем
function setUpgradePrice(uint level, uint price) external onlyOwner { require(price != 0); _upgradePrices[level] = price; }
1,791,169
[ 1, 20, 225, 146, 228, 146, 230, 145, 125, 145, 125, 146, 238, 300, 225, 145, 126, 145, 118, 225, 145, 128, 146, 227, 145, 121, 145, 126, 145, 121, 145, 125, 145, 113, 145, 118, 145, 125, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 10784, 5147, 12, 11890, 1801, 16, 2254, 6205, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 8694, 480, 374, 1769, 203, 203, 3639, 389, 15097, 31862, 63, 2815, 65, 273, 6205, 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 ]
/** Copyright (c) 2018 SmartTaylor 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. based on the contracts of OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts **/ pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** @title TaylorToken **/ contract TaylorToken is Ownable{ using SafeMath for uint256; /** EVENTS **/ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed _owner, uint256 _amount); /** CONTRACT VARIABLES **/ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; //this address can transfer even when transfer is disabled. mapping (address => bool) public whitelistedTransfer; mapping (address => bool) public whitelistedBurn; string public name = "Taylor"; string public symbol = "TAY"; uint8 public decimals = 18; uint256 constant internal DECIMAL_CASES = 10**18; uint256 public totalSupply = 10**7 * DECIMAL_CASES; bool public transferable = false; /** MODIFIERS **/ modifier onlyWhenTransferable(){ if(!whitelistedTransfer[msg.sender]){ require(transferable); } _; } /** CONSTRUCTOR **/ /** @dev Constructor function executed on contract creation **/ function TaylorToken() Ownable() public { balances[owner] = balances[owner].add(totalSupply); whitelistedTransfer[msg.sender] = true; whitelistedBurn[msg.sender] = true; Transfer(address(0),owner, totalSupply); } /** OWNER ONLY FUNCTIONS **/ /** @dev Activates the trasfer for all users **/ function activateTransfers() public onlyOwner { transferable = true; } /** @dev Allows the owner to add addresse that can bypass the transfer lock. Eg: ICO contract, TGE contract. @param _address address Address to be added **/ function addWhitelistedTransfer(address _address) public onlyOwner { whitelistedTransfer[_address] = true; } /** @dev Sends all avaible TAY to the TGE contract to be properly distribute @param _tgeAddress address Address of the token distribution contract **/ function distribute(address _tgeAddress) public onlyOwner { whitelistedTransfer[_tgeAddress] = true; transfer(_tgeAddress, balances[owner]); } /** @dev Allows the owner to add addresse that can burn tokens Eg: ICO contract, TGE contract. @param _address address Address to be added **/ function addWhitelistedBurn(address _address) public onlyOwner { whitelistedBurn[_address] = true; } /** PUBLIC FUNCTIONS **/ /** * @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 onlyWhenTransferable returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); 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 amount of tokens to be transferred */ function transferFrom (address _from, address _to, uint256 _value) public onlyWhenTransferable returns (bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. For security reasons, if one need to change the value from a existing allowance, it must furst sets it to zero and then sets the new value * @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 onlyWhenTransferable returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** @dev Allows for msg.sender to burn his on tokens @param _amount uint256 The amount of tokens to be burned **/ function burn(uint256 _amount) public returns (bool success) { require(whitelistedBurn[msg.sender]); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); totalSupply = totalSupply.sub(_amount); Burn(msg.sender, _amount); return true; } /** CONSTANT FUNCTIONS **/ /** * @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) view public returns (uint256 balance) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */ contract TokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); // beneficiary of tokens after they are released address public beneficiary; TaylorToken public token; uint256 public cliff; uint256 public start; uint256 public duration; uint256 public released; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _token The token to be vested */ function TokenVesting(address _beneficiary,address _token, uint256 _start, uint256 _cliff, uint256 _duration) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; duration = _duration; token = TaylorToken(_token); cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0); released = released.add(unreleased); token.transfer(beneficiary, unreleased); Released(unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return vestedAmount().sub(released); } /** * @dev Calculates the amount that has already vested. */ function vestedAmount() public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released); if (now < cliff) { return 0; } else if (now >= cliff && now < start.add(duration)) { return totalBalance / 2; } else { return totalBalance; } } }
* @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; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } @param _amount uint256 The amount of tokens to be burned
475,140
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 1717, 1575, 329, 620, 13, 203, 1377, 1071, 203, 1377, 1135, 261, 6430, 13, 203, 565, 288, 203, 1377, 2254, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 1377, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 1377, 289, 203, 1377, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 203, 1377, 327, 638, 31, 203, 565, 289, 203, 203, 1377, 632, 891, 389, 8949, 2254, 5034, 1021, 3844, 434, 2430, 358, 506, 18305, 329, 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 ]
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner 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; } } /************************************************************** * @title Scale Token Contract * @file Scale.sol * @author Jared Downing and Kane Thomas of the Scale Network * @version 1.0 * * @section DESCRIPTION * * This is an ERC20-based token with staking and inflationary functionality. * *************************************************************/ ////////////////////////////////// /// OpenZeppelin library imports ////////////////////////////////// /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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 Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol * Modified to allow minting for non-owner addresses */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(address(this).balance)); } } ////////////////////////////////// /// Scale Token ////////////////////////////////// contract Scale is MintableToken, HasNoEther { // Libraries using SafeMath for uint; ////////////////////// // Token Information ////////////////////// string public constant name = "SCALE"; string public constant symbol = "SCALE"; uint8 public constant decimals = 18; /////////////////////////////////////////////////////////// // Variables For Staking and Pooling /////////////////////////////////////////////////////////// // -- Pool Minting Rates and Percentages -- // // Pool for Scale distribution to rewards pool // Set to 0 to prohibit issuing to the pool before it is assigned address public pool = address(0); // Pool and Owner minted tokens per second uint public poolMintRate; uint public ownerMintRate; // Amount of Scale to be staked to the pool, staking, and mint, as calculated through their percentages uint public poolMintAmount; uint public stakingMintAmount; uint public ownerMintAmount; // Scale distribution percentages uint public poolPercentage = 70; uint public ownerPercentage = 5; uint public stakingPercentage = 25; // Last time minted for owner and pool uint public ownerTimeLastMinted; uint public poolTimeLastMinted; // -- Staking -- // // Minted tokens per second uint public stakingMintRate; // Total Scale currently staked uint public totalScaleStaked; // Mapping of the timestamp => totalStaking that is created each time an address stakes or unstakes mapping (uint => uint) totalStakingHistory; // Variable for staking accuracy. Set to 86400 for seconds in a day so that staking gains are based on the day an account begins staking. uint timingVariable = 86400; // Address staking information struct AddressStakeData { uint stakeBalance; uint initialStakeTime; } // Track all tokens staked mapping (address => AddressStakeData) public stakeBalances; // -- Inflation -- // // Inflation rate begins at 100% per year and decreases by 15% per year until it reaches 10% where it decreases by 0.5% per year uint256 inflationRate = 1000; // Used to manage when to inflate. Allowed to inflate once per year until the rate reaches 1%. uint256 public lastInflationUpdate; // -- Events -- // // Fired when tokens are staked event Stake(address indexed staker, uint256 value); // Fired when tokens are unstaked event Unstake(address indexed unstaker, uint256 stakedAmount, uint256 stakingGains); ////////////////////////////////////////////////// /// Scale Token Functionality ////////////////////////////////////////////////// /// @dev Scale token constructor constructor() public { // Assign owner owner = msg.sender; // Assign initial owner supply uint _initOwnerSupply = 10000000 ether; // Mint given to owner only one-time bool _success = mint(msg.sender, _initOwnerSupply); // Require minting success require(_success); // Set pool and owner last minted to ensure extra coins are not minted by either ownerTimeLastMinted = now; poolTimeLastMinted = now; // Set minting amount for pool, staking, and owner over the course of 1 year poolMintAmount = _initOwnerSupply.mul(poolPercentage).div(100); ownerMintAmount = _initOwnerSupply.mul(ownerPercentage).div(100); stakingMintAmount = _initOwnerSupply.mul(stakingPercentage).div(100); // One year in seconds uint _oneYearInSeconds = 31536000 ether; // Set the rate of coins minted per second for the pool, owner, and global staking poolMintRate = calculateFraction(poolMintAmount, _oneYearInSeconds, decimals); ownerMintRate = calculateFraction(ownerMintAmount, _oneYearInSeconds, decimals); stakingMintRate = calculateFraction(stakingMintAmount, _oneYearInSeconds, decimals); // Set the last time inflation was update to now so that the next time it can be updated is 1 year from now lastInflationUpdate = now; } ///////////// // Inflation ///////////// /// @dev the inflation rate begins at 100% and decreases by 15% every year until it reaches 10% /// at 10% the rate begins to decrease by 0.5% until it reaches 1% function adjustInflationRate() private { // Make sure adjustInflationRate cannot be called for at least another year lastInflationUpdate = now; // Decrease inflation rate by 15% each year if (inflationRate > 100) { inflationRate = inflationRate.sub(300); } // Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%. else if (inflationRate > 10) { inflationRate = inflationRate.sub(5); } // Calculate new mint amount of Scale that should be created per year. // Example Inflation Past Year 1 for the poolMintAmount: 16M * 0.85 * 0.7 = 9,520,000 poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100); ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100); stakingMintAmount = totalSupply.mul(inflationRate).div(1000).mul(stakingPercentage).div(100); // Adjust Scale created per-second for each rate poolMintRate = calculateFraction(poolMintAmount, 31536000 ether, decimals); ownerMintRate = calculateFraction(ownerMintAmount, 31536000 ether, decimals); stakingMintRate = calculateFraction(stakingMintAmount, 31536000 ether, decimals); } /// @dev anyone can call this function to update the inflation rate yearly function updateInflationRate() public { // Require 1 year to have passed for every inflation adjustment require(now.sub(lastInflationUpdate) >= 31536000); adjustInflationRate(); } ///////////// // Staking ///////////// /// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 30 days /// @param _stakeAmount how many tokens a user wants to stake function stakeScale(uint _stakeAmount) external { // Require that tokens are staked successfully require(stake(msg.sender, _stakeAmount)); } /// @dev stake for a seperate address /// @param _stakeAmount how many tokens a user wants to stake function stakeFor(address _user, uint _stakeAmount) external { // You can only stake tokens for another user if they have not already staked tokens require(stakeBalances[_user].stakeBalance == 0); // Transfer Scale from to the user transfer( _user, _stakeAmount); // Stake for the user stake(_user, _stakeAmount); } /// @dev stake function reduces the user's total available balance and adds it to their staking balance /// @param _value how many tokens a user wants to stake function stake(address _user, uint256 _value) private returns (bool success) { // You can only stake as many tokens as you have require(_value <= balances[_user]); // You can only stake tokens if you have not already staked tokens require(stakeBalances[_user].stakeBalance == 0); // Subtract stake amount from regular token balance balances[_user] = balances[_user].sub(_value); // Add stake amount to staked balance stakeBalances[_user].stakeBalance = _value; // Increment the staking staked tokens value totalScaleStaked = totalScaleStaked.add(_value); // Save the time that the stake started stakeBalances[_user].initialStakeTime = now.div(timingVariable); // Set the new staking history setTotalStakingHistory(); // Fire an event to tell the world of the newly staked tokens emit Stake(_user, _value); return true; } /// @dev returns how much Scale a user has earned so far /// @param _now is passed in to allow for a gas-free analysis /// @return staking gains based on the amount of time passed since staking began function getStakingGains(uint _now) view public returns (uint) { if (stakeBalances[msg.sender].stakeBalance == 0) { return 0; } return calculateStakeGains(_now); } /// @dev allows users to reclaim any staked tokens /// @return bool on success function unstake() external returns (bool) { // Require that there was some amount vested require(stakeBalances[msg.sender].stakeBalance > 0); // Require that at least 7 timing variables have passed (days) require(now.div(timingVariable).sub(stakeBalances[msg.sender].initialStakeTime) >= 7); // Calculate tokens to mint uint _tokensToMint = calculateStakeGains(now); balances[msg.sender] = balances[msg.sender].add(stakeBalances[msg.sender].stakeBalance); // Subtract stake balance from totalScaleStaked totalScaleStaked = totalScaleStaked.sub(stakeBalances[msg.sender].stakeBalance); // Mint the new tokens to the sender mint(msg.sender, _tokensToMint); // Scale unstaked event emit Unstake(msg.sender, stakeBalances[msg.sender].stakeBalance, _tokensToMint); // Clear out stored data from mapping stakeBalances[msg.sender].stakeBalance = 0; stakeBalances[msg.sender].initialStakeTime = 0; // Set this every time someone adjusts the totalScaleStaking amount setTotalStakingHistory(); return true; } /// @dev Helper function to claimStake that modularizes the minting via staking calculation /// @param _now when the user stopped staking. Passed in as a variable to allow for checking without using gas from the getStakingGains function. /// @return uint for total coins to be minted function calculateStakeGains(uint _now) view private returns (uint mintTotal) { uint _nowAsTimingVariable = _now.div(timingVariable); // Today as a unique value in unix time uint _initialStakeTimeInVariable = stakeBalances[msg.sender].initialStakeTime; // When the user started staking as a unique day in unix time uint _timePassedSinceStakeInVariable = _nowAsTimingVariable.sub(_initialStakeTimeInVariable); // How much time has passed, in days, since the user started staking. uint _stakePercentages = 0; // Keeps an additive track of the user's staking percentages over time uint _tokensToMint = 0; // How many new Scale tokens to create uint _lastUsedVariable; // Last day the totalScaleStaked was updated // Average this msg.sender's relative percentage ownership of totalScaleStaked throughout each day since they started staking for (uint i = _initialStakeTimeInVariable; i < _nowAsTimingVariable; i++) { // If the day exists add it to the percentages if (totalStakingHistory[i] != 0) { // If the day does exist add it to the number to be later averaged as a total average percentage of total staking _stakePercentages = _stakePercentages.add(calculateFraction(stakeBalances[msg.sender].stakeBalance, totalStakingHistory[i], decimals)); // Set this as the last day someone staked _lastUsedVariable = totalStakingHistory[i]; } else { // Use the last day found in the totalStakingHistory mapping _stakePercentages = _stakePercentages.add(calculateFraction(stakeBalances[msg.sender].stakeBalance, _lastUsedVariable, decimals)); } } // Get the account's average percentage staked of the total stake over the course of all days they have been staking uint _stakePercentageAverage = calculateFraction(_stakePercentages, _timePassedSinceStakeInVariable, 0); // Calculate this account's mint rate per second while staking uint _finalMintRate = stakingMintRate.mul(_stakePercentageAverage); // Account for 18 decimals when calculating the amount of tokens to mint _finalMintRate = _finalMintRate.div(1 ether); // Calculate total tokens to be minted. Multiply by timingVariable to convert back to seconds. if (_timePassedSinceStakeInVariable >= 365) { // Tokens were staked for the maximum amount of time, one year. Give them one year's worth of tokens. ( this limit is placed to avoid gas limits) _tokensToMint = calculateMintTotal(timingVariable.mul(365), _finalMintRate); } else { // Tokens were staked for less than the maximum amount of time _tokensToMint = calculateMintTotal(_timePassedSinceStakeInVariable.mul(timingVariable), _finalMintRate); } return _tokensToMint; } /// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked function setTotalStakingHistory() private { // Get now in terms of the variable staking accuracy (days in Scale's case) uint _nowAsTimingVariable = now.div(timingVariable); // Set the totalStakingHistory as a timestamp of the totalScaleStaked today totalStakingHistory[_nowAsTimingVariable] = totalScaleStaked; } /// @dev Allows user to check their staked balance /// @return staked balance function getStakedBalance() view external returns (uint stakedBalance) { return stakeBalances[msg.sender].stakeBalance; } ///////////// // Scale Owner Claiming ///////////// /// @dev allows contract owner to claim their mint function ownerClaim() external onlyOwner { require(now > ownerTimeLastMinted); uint _timePassedSinceLastMint; // The amount of time passed since the owner claimed in seconds uint _tokenMintCount; // The amount of new tokens to mint bool _mintingSuccess; // The success of minting the new Scale tokens // Calculate the number of seconds that have passed since the owner last took a claim _timePassedSinceLastMint = now.sub(ownerTimeLastMinted); assert(_timePassedSinceLastMint > 0); // Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate _tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate); // Mint the owner's tokens; this also increases totalSupply _mintingSuccess = mint(msg.sender, _tokenMintCount); require(_mintingSuccess); // New minting was a success. Set last time minted to current block.timestamp (now) ownerTimeLastMinted = now; } //////////////////////////////// // Scale Pool Distribution //////////////////////////////// /// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool function poolIssue() public { // Do not allow tokens to be minted to the pool until the pool is set require(pool != address(0)); // Make sure time has passed since last minted to pool require(now > poolTimeLastMinted); require(pool != address(0)); uint _timePassedSinceLastMint; // The amount of time passed since the pool claimed in seconds uint _tokenMintCount; // The amount of new tokens to mint bool _mintingSuccess; // The success of minting the new Scale tokens // Calculate the number of seconds that have passed since the owner last took a claim _timePassedSinceLastMint = now.sub(poolTimeLastMinted); assert(_timePassedSinceLastMint > 0); // Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate _tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, poolMintRate); // Mint the owner's tokens; this also increases totalSupply _mintingSuccess = mint(pool, _tokenMintCount); require(_mintingSuccess); // New minting was a success! Set last time minted to current block.timestamp (now) poolTimeLastMinted = now; } /// @dev sets the address for the rewards pool /// @param _newAddress pool Address function setPool(address _newAddress) public onlyOwner { pool = _newAddress; } //////////////////////////////// // Helper Functions //////////////////////////////// /// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type /// @param _numerator is the top part of the fraction we are calculating /// @param _denominator is the bottom part of the fraction we are calculating /// @param _precision tells the function how many significant digits to calculate out to /// @return quotient returns the result of our fraction calculation function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient) { // Take passed value and expand it to the required precision _numerator = _numerator.mul(10 ** (_precision + 1)); // Handle last-digit rounding uint _quotient = ((_numerator.div(_denominator)) + 5) / 10; return (_quotient); } /// @dev Determines the amount of Scale to create based on the number of seconds that have passed /// @param _timeInSeconds is the time passed in seconds to mint for /// @return uint with the calculated number of new tokens to mint function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) { // Calculates the amount of tokens to mint based upon the number of seconds passed return(_timeInSeconds.mul(_mintRate)); } }
Calculate this account's mint rate per second while staking
uint _finalMintRate = stakingMintRate.mul(_stakePercentageAverage);
5,502,180
[ 1, 8695, 333, 2236, 1807, 312, 474, 4993, 1534, 2205, 1323, 384, 6159, 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, 3639, 2254, 389, 6385, 49, 474, 4727, 273, 384, 6159, 49, 474, 4727, 18, 16411, 24899, 334, 911, 16397, 17115, 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 ]
./partial_match/1/0xFA582247330730604A48cD7138AFd8cd740B100d/sources/TAU.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract TAU is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Automata", "TAU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 60; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 60; uint256 _sellMarketingFee = 60; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 60; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 90, "Must keep fees at 90% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 90, "Must keep fees at 90% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / (success, ) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
2,673,584
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 14237, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 2 ]
pragma solidity ^0.4.24; /** * @title ERC20Basic * dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * dev Math operations with safety checks that throw on error */ library SafeMath { /** * dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0), "Recipient address is zero address(0). Check the address again."); require(_value <= balances[msg.sender], "The balance of account is insufficient."); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0), "Recipient address is zero address(0). Check the address again."); require(_value <= balances[_from], "The balance of account is insufficient."); require(_value <= allowed[_from][msg.sender], "Insufficient tokens approved from account owner."); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title MultiOwnable * dev */ contract MultiOwnable { using SafeMath for uint256; address public root; // 혹시 몰라 준비해둔 superOwner 의 백업. 하드웨어 월렛 주소로 세팅할 예정. address public superOwner; mapping (address => bool) public owners; address[] public ownerList; // for changeSuperOwnerByDAO // mapping(address => mapping (address => bool)) public preSuperOwnerMap; mapping(address => address) public candidateSuperOwnerMap; event ChangedRoot(address newRoot); event ChangedSuperOwner(address newSuperOwner); event AddedNewOwner(address newOwner); event DeletedOwner(address deletedOwner); constructor() public { root = msg.sender; superOwner = msg.sender; owners[root] = true; ownerList.push(msg.sender); } modifier onlyRoot() { require(msg.sender == root, "Root privilege is required."); _; } modifier onlySuperOwner() { require(msg.sender == superOwner, "SuperOwner priviledge is required."); _; } modifier onlyOwner() { require(owners[msg.sender], "Owner priviledge is required."); _; } /** * dev root 교체 (root 는 root 와 superOwner 를 교체할 수 있는 권리가 있다.) * dev 기존 루트가 관리자에서 지워지지 않고, 새 루트가 자동으로 관리자에 등록되지 않음을 유의! */ function changeRoot(address newRoot) onlyRoot public returns (bool) { require(newRoot != address(0), "This address to be set is zero address(0). Check the input address."); root = newRoot; emit ChangedRoot(newRoot); return true; } /** * dev superOwner 교체 (root 는 root 와 superOwner 를 교체할 수 있는 권리가 있다.) * dev 기존 superOwner 가 관리자에서 지워지지 않고, 새 superOwner 가 자동으로 관리자에 등록되지 않음을 유의! */ function changeSuperOwner(address newSuperOwner) onlyRoot public returns (bool) { require(newSuperOwner != address(0), "This address to be set is zero address(0). Check the input address."); superOwner = newSuperOwner; emit ChangedSuperOwner(newSuperOwner); return true; } /** * dev owner 들의 1/2 초과가 합의하면 superOwner 를 교체할 수 있다. */ function changeSuperOwnerByDAO(address newSuperOwner) onlyOwner public returns (bool) { require(newSuperOwner != address(0), "This address to be set is zero address(0). Check the input address."); require(newSuperOwner != candidateSuperOwnerMap[msg.sender], "You have already voted for this account."); candidateSuperOwnerMap[msg.sender] = newSuperOwner; uint8 votingNumForSuperOwner = 0; uint8 i = 0; for (i = 0; i < ownerList.length; i++) { if (candidateSuperOwnerMap[ownerList[i]] == newSuperOwner) votingNumForSuperOwner++; } if (votingNumForSuperOwner > ownerList.length / 2) { // 과반수 이상이면 DAO 성립 => superOwner 교체 superOwner = newSuperOwner; // 초기화 for (i = 0; i < ownerList.length; i++) { delete candidateSuperOwnerMap[ownerList[i]]; } emit ChangedSuperOwner(newSuperOwner); } return true; } function newOwner(address owner) onlySuperOwner public returns (bool) { require(owner != address(0), "This address to be set is zero address(0). Check the input address."); require(!owners[owner], "This address is already registered."); owners[owner] = true; ownerList.push(owner); emit AddedNewOwner(owner); return true; } function deleteOwner(address owner) onlySuperOwner public returns (bool) { require(owners[owner], "This input address is not a super owner."); delete owners[owner]; for (uint256 i = 0; i < ownerList.length; i++) { if (ownerList[i] == owner) { ownerList[i] = ownerList[ownerList.length.sub(1)]; ownerList.length = ownerList.length.sub(1); break; } } emit DeletedOwner(owner); return true; } } /** * @title Lockable token */ contract LockableToken is StandardToken, MultiOwnable { bool public locked = true; uint256 public constant LOCK_MAX = uint256(-1); /** * dev 락 상태에서도 거래 가능한 언락 계정 */ mapping(address => bool) public unlockAddrs; /** * dev 계정 별로 lock value 만큼 잔고가 잠김 * dev - 값이 0 일 때 : 잔고가 0 이어도 되므로 제한이 없는 것임. * dev - 값이 LOCK_MAX 일 때 : 잔고가 uint256 의 최대값이므로 아예 잠긴 것임. */ mapping(address => uint256) public lockValues; event Locked(bool locked, string note); event LockedTo(address indexed addr, bool locked, string note); event SetLockValue(address indexed addr, uint256 value, string note); constructor() public { unlockTo(msg.sender, ""); } modifier checkUnlock (address addr, uint256 value) { require(!locked || unlockAddrs[addr], "The account is currently locked."); require(balances[addr].sub(value) >= lockValues[addr], "Transferable limit exceeded. Check the status of the lock value."); _; } function lock(string note) onlyOwner public { locked = true; emit Locked(locked, note); } function unlock(string note) onlyOwner public { locked = false; emit Locked(locked, note); } function lockTo(address addr, string note) onlyOwner public { setLockValue(addr, LOCK_MAX, note); unlockAddrs[addr] = false; emit LockedTo(addr, true, note); } function unlockTo(address addr, string note) onlyOwner public { if (lockValues[addr] == LOCK_MAX) setLockValue(addr, 0, note); unlockAddrs[addr] = true; emit LockedTo(addr, false, note); } function setLockValue(address addr, uint256 value, string note) onlyOwner public { lockValues[addr] = value; emit SetLockValue(addr, value, note); } /** * dev 이체 가능 금액을 조회한다. */ function getMyUnlockValue() public view returns (uint256) { address addr = msg.sender; if ((!locked || unlockAddrs[addr]) && balances[addr] > lockValues[addr]) return balances[addr].sub(lockValues[addr]); else return 0; } function transfer(address to, uint256 value) checkUnlock(msg.sender, value) public returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) checkUnlock(from, value) public returns (bool) { return super.transferFrom(from, to, value); } } /** * @title DelayLockableToken * dev 보안 차원에서 본인 계좌 잔고에 lock 을 걸 수 있다. 잔고 제한 기준을 낮추면 적용되기까지 12시간을 기다려야 한다. */ contract DelayLockableToken is LockableToken { mapping(address => uint256) public delayLockValues; mapping(address => uint256) public delayLockBeforeValues; mapping(address => uint256) public delayLockTimes; event SetDelayLockValue(address indexed addr, uint256 value, uint256 time); modifier checkDelayUnlock (address addr, uint256 value) { if (delayLockTimes[msg.sender] <= now) { require (balances[addr].sub(value) >= delayLockValues[addr], "Transferable limit exceeded. Change the balance lock value first and then use it"); } else { require (balances[addr].sub(value) >= delayLockBeforeValues[addr], "Transferable limit exceeded. Please note that the residual lock value has changed and it will take 12 hours to apply."); } _; } /** * dev 자신의 계좌에 잔고 제한을 건다. 더 크게 걸 땐 바로 적용되고, 더 작게 걸 땐 12시간 이후에 변경된다. */ function delayLock(uint256 value) public returns (bool) { require (value <= balances[msg.sender], "Your balance is insufficient."); if (value >= delayLockValues[msg.sender]) delayLockTimes[msg.sender] = now; else { require (delayLockTimes[msg.sender] <= now, "The remaining money in the account cannot be unlocked continuously. You cannot renew until 12 hours after the first run."); delayLockTimes[msg.sender] = now + 12 hours; delayLockBeforeValues[msg.sender] = delayLockValues[msg.sender]; } delayLockValues[msg.sender] = value; emit SetDelayLockValue(msg.sender, value, delayLockTimes[msg.sender]); return true; } /** * dev 자신의 계좌의 잔고 제한을 푼다. */ function delayUnlock() public returns (bool) { return delayLock(0); } /** * dev 이체 가능 금액을 조회한다. */ function getMyUnlockValue() public view returns (uint256) { uint256 myUnlockValue; address addr = msg.sender; if (delayLockTimes[addr] <= now) { myUnlockValue = balances[addr].sub(delayLockValues[addr]); } else { myUnlockValue = balances[addr].sub(delayLockBeforeValues[addr]); } uint256 superUnlockValue = super.getMyUnlockValue(); if (myUnlockValue > superUnlockValue) return superUnlockValue; else return myUnlockValue; } function transfer(address to, uint256 value) checkDelayUnlock(msg.sender, value) public returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) checkDelayUnlock(from, value) public returns (bool) { return super.transferFrom(from, to, value); } } /** * @title KSCBaseToken * dev 트랜잭션 실행 시 메모를 남길 수 있도록 하였음. */ contract KSCBaseToken is DelayLockableToken { event KSCTransfer(address indexed from, address indexed to, uint256 value, string note); event KSCTransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event KSCApproval(address indexed owner, address indexed spender, uint256 value, string note); event KSCMintTo(address indexed controller, address indexed to, uint256 amount, string note); event KSCBurnFrom(address indexed controller, address indexed from, uint256 value, string note); event KSCBurnWhenMoveToMainnet(address indexed controller, address indexed from, uint256 value, string note); event KSCSell(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event KSCSellByOtherCoin(address indexed owner, address indexed spender, address indexed to, uint256 value, uint256 processIdHash, uint256 userIdHash, string note); event KSCTransferToTeam(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event KSCTransferToPartner(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event KSCTransferToEcosystem(address indexed owner, address indexed spender, address indexed to, uint256 value, uint256 processIdHash, uint256 userIdHash, string note); event KSCTransferToBounty(address indexed owner, address indexed spender, address indexed to, uint256 value, uint256 processIdHash, uint256 userIdHash, string note); // ERC20 함수들을 오버라이딩하여 super 로 올라가지 않고 무조건 ksc~ 함수로 지나가게 한다. function transfer(address to, uint256 value) public returns (bool ret) { return kscTransfer(to, value, ""); } function kscTransfer(address to, uint256 value, string note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = super.transfer(to, value); emit KSCTransfer(msg.sender, to, value, note); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return kscTransferFrom(from, to, value, ""); } function kscTransferFrom(address from, address to, uint256 value, string note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = super.transferFrom(from, to, value); emit KSCTransferFrom(from, msg.sender, to, value, note); } function approve(address spender, uint256 value) public returns (bool) { return kscApprove(spender, value, ""); } function kscApprove(address spender, uint256 value, string note) public returns (bool ret) { ret = super.approve(spender, value); emit KSCApproval(msg.sender, spender, value, note); } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { return kscIncreaseApproval(spender, addedValue, ""); } function kscIncreaseApproval(address spender, uint256 addedValue, string note) public returns (bool ret) { ret = super.increaseApproval(spender, addedValue); emit KSCApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { return kscDecreaseApproval(spender, subtractedValue, ""); } function kscDecreaseApproval(address spender, uint256 subtractedValue, string note) public returns (bool ret) { ret = super.decreaseApproval(spender, subtractedValue); emit KSCApproval(msg.sender, spender, allowed[msg.sender][spender], note); } /** * dev 신규 화폐 발행. 반드시 이유를 메모로 남겨라. */ function mintTo(address to, uint256 amount) internal returns (bool) { require(to != address(0x0), "This address to be set is zero address(0). Check the input address."); totalSupply_ = totalSupply_.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function kscMintTo(address to, uint256 amount, string note) onlyOwner public returns (bool ret) { ret = mintTo(to, amount); emit KSCMintTo(msg.sender, to, amount, note); } /** * dev 화폐 소각. 반드시 이유를 메모로 남겨라. */ function burnFrom(address from, uint256 value) internal returns (bool) { require(value <= balances[from], "Your balance is insufficient."); balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); emit Transfer(from, address(0), value); return true; } function kscBurnFrom(address from, uint256 value, string note) onlyOwner public returns (bool ret) { ret = burnFrom(from, value); emit KSCBurnFrom(msg.sender, from, value, note); } /** * dev 메인넷으로 이동하며 화폐 소각. */ function kscBurnWhenMoveToMainnet(address burner, uint256 value, string note) onlyOwner public returns (bool ret) { ret = burnFrom(burner, value); emit KSCBurnWhenMoveToMainnet(msg.sender, burner, value, note); } function kscBatchBurnWhenMoveToMainnet(address[] burners, uint256[] values, string note) onlyOwner public returns (bool ret) { uint256 length = burners.length; require(length == values.length, "The size of \'burners\' and \'values\' array is different."); ret = true; for (uint256 i = 0; i < length; i++) { ret = ret && kscBurnWhenMoveToMainnet(burners[i], values[i], note); } } /** * dev 이더로 KSC 를 구입하는 경우 */ function kscSell( address from, address to, uint256 value, string note ) onlyOwner public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = super.transferFrom(from, to, value); emit KSCSell(from, msg.sender, to, value, note); } /** * dev 비트코인 등의 다른 코인으로 KSC 를 구입하는 경우 * dev EOA 가 트랜잭션을 일으켜서 처리해야 하기 때문에 다계좌를 기준으로 한다. (가스비 아끼기 위함) */ function kscBatchSellByOtherCoin( address from, address[] to, uint256[] values, uint256 processIdHash, uint256[] userIdHash, string note ) onlyOwner public returns (bool ret) { uint256 length = to.length; require(length == values.length, "The size of \'to\' and \'values\' array is different."); require(length == userIdHash.length, "The size of \'to\' and \'userIdHash\' array is different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = ret && super.transferFrom(from, to[i], values[i]); emit KSCSellByOtherCoin(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } /** * dev 팀에게 전송하는 경우 */ function kscTransferToTeam( address from, address to, uint256 value, string note ) onlyOwner public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = super.transferFrom(from, to, value); emit KSCTransferToTeam(from, msg.sender, to, value, note); } /** * dev 파트너 및 어드바이저에게 전송하는 경우 */ function kscTransferToPartner( address from, address to, uint256 value, string note ) onlyOwner public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = super.transferFrom(from, to, value); emit KSCTransferToPartner(from, msg.sender, to, value, note); } /** * dev 에코시스템(커뮤니티 활동을 통한 보상 등)으로 KSC 지급 * dev EOA 가 트랜잭션을 일으켜서 처리해야 하기 때문에 다계좌를 기준으로 한다. (가스비 아끼기 위함) */ function kscBatchTransferToEcosystem( address from, address[] to, uint256[] values, uint256 processIdHash, uint256[] userIdHash, string note ) onlyOwner public returns (bool ret) { uint256 length = to.length; require(length == values.length, "The size of \'to\' and \'values\' array is different."); require(length == userIdHash.length, "The size of \'to\' and \'userIdHash\' array is different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = ret && super.transferFrom(from, to[i], values[i]); emit KSCTransferToEcosystem(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } /** * dev 바운티 참여자에게 KSC 지급 * dev EOA 가 트랜잭션을 일으켜서 처리해야 하기 때문에 다계좌를 기준으로 한다. (가스비 아끼기 위함) */ function kscBatchTransferToBounty( address from, address[] to, uint256[] values, uint256 processIdHash, uint256[] userIdHash, string note ) onlyOwner public returns (bool ret) { uint256 length = to.length; require(to.length == values.length, "The size of \'to\' and \'values\' array is different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of KStarCoin. You cannot send money to this address."); ret = ret && super.transferFrom(from, to[i], values[i]); emit KSCTransferToBounty(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } function destroy() onlyRoot public { selfdestruct(root); } } /** * @title KStarCoin */ contract KStarCoin is KSCBaseToken { using AddressUtils for address; event TransferedToKSCDapp( address indexed owner, address indexed spender, address indexed to, uint256 value, KSCReceiver.KSCReceiveType receiveType); string public constant name = "KStarCoin"; string public constant symbol = "KSC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1e9 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function kscTransfer(address to, uint256 value, string note) public returns (bool ret) { ret = super.kscTransfer(to, value, note); postTransfer(msg.sender, msg.sender, to, value, KSCReceiver.KSCReceiveType.KSC_TRANSFER); } function kscTransferFrom(address from, address to, uint256 value, string note) public returns (bool ret) { ret = super.kscTransferFrom(from, to, value, note); postTransfer(from, msg.sender, to, value, KSCReceiver.KSCReceiveType.KSC_TRANSFER); } function postTransfer(address owner, address spender, address to, uint256 value, KSCReceiver.KSCReceiveType receiveType) internal returns (bool) { if (to.isContract()) { bool callOk = address(to).call(bytes4(keccak256("onKSCReceived(address,address,uint256,uint8)")), owner, spender, value, receiveType); if (callOk) { emit TransferedToKSCDapp(owner, spender, to, value, receiveType); } } return true; } function kscMintTo(address to, uint256 amount, string note) onlyOwner public returns (bool ret) { ret = super.kscMintTo(to, amount, note); postTransfer(0x0, msg.sender, to, amount, KSCReceiver.KSCReceiveType.KSC_MINT); } function kscBurnFrom(address from, uint256 value, string note) onlyOwner public returns (bool ret) { ret = super.kscBurnFrom(from, value, note); postTransfer(0x0, msg.sender, from, value, KSCReceiver.KSCReceiveType.KSC_BURN); } } /** * @title KStarCoin Receiver */ contract KSCReceiver { enum KSCReceiveType { KSC_TRANSFER, KSC_MINT, KSC_BURN } function onKSCReceived(address owner, address spender, uint256 value, KSCReceiveType receiveType) public returns (bool); } /** * @title KSCDappSample */ contract KSCDappSample is KSCReceiver { event LogOnReceiveKSC(string message, address indexed owner, address indexed spender, uint256 value, KSCReceiveType receiveType); function onKSCReceived(address owner, address spender, uint256 value, KSCReceiveType receiveType) public returns (bool) { emit LogOnReceiveKSC("I receive KstarCoin.", owner, spender, value, receiveType); return true; } }
* dev 자신의 계좌에 잔고 제한을 건다. 더 크게 걸 땐 바로 적용되고, 더 작게 걸 땐 12시간 이후에 변경된다./
function delayLock(uint256 value) public returns (bool) { require (value <= balances[msg.sender], "Your balance is insufficient."); if (value >= delayLockValues[msg.sender]) delayLockTimes[msg.sender] = now; else { require (delayLockTimes[msg.sender] <= now, "The remaining money in the account cannot be unlocked continuously. You cannot renew until 12 hours after the first run."); delayLockTimes[msg.sender] = now + 12 hours; delayLockBeforeValues[msg.sender] = delayLockValues[msg.sender]; } delayLockValues[msg.sender] = value; emit SetDelayLockValue(msg.sender, value, delayLockTimes[msg.sender]); return true; }
12,849,216
[ 1, 5206, 225, 173, 257, 243, 173, 238, 259, 173, 256, 251, 225, 171, 116, 231, 173, 100, 239, 173, 250, 243, 225, 173, 257, 247, 171, 116, 259, 225, 173, 259, 255, 174, 248, 255, 173, 256, 231, 225, 171, 114, 117, 172, 238, 102, 18, 225, 172, 240, 247, 225, 174, 228, 110, 171, 115, 239, 225, 171, 114, 121, 225, 172, 248, 243, 225, 172, 113, 247, 172, 99, 255, 225, 173, 259, 228, 173, 253, 107, 172, 243, 251, 171, 116, 259, 16, 225, 172, 240, 247, 225, 173, 257, 244, 171, 115, 239, 225, 171, 114, 121, 225, 172, 248, 243, 2593, 173, 238, 255, 171, 113, 231, 225, 173, 256, 117, 174, 254, 231, 173, 250, 243, 225, 172, 116, 227, 171, 115, 126, 172, 243, 255, 172, 238, 102, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4624, 2531, 12, 11890, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 261, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 6487, 315, 15446, 11013, 353, 2763, 11339, 1199, 1769, 203, 203, 3639, 309, 261, 1132, 1545, 4624, 2531, 1972, 63, 3576, 18, 15330, 5717, 203, 5411, 4624, 2531, 10694, 63, 3576, 18, 15330, 65, 273, 2037, 31, 203, 3639, 469, 288, 203, 5411, 2583, 261, 10790, 2531, 10694, 63, 3576, 18, 15330, 65, 1648, 2037, 16, 315, 1986, 4463, 15601, 316, 326, 2236, 2780, 506, 25966, 17235, 715, 18, 4554, 2780, 15723, 3180, 2593, 7507, 1839, 326, 1122, 1086, 1199, 1769, 203, 5411, 4624, 2531, 10694, 63, 3576, 18, 15330, 65, 273, 2037, 397, 2593, 7507, 31, 203, 5411, 4624, 2531, 4649, 1972, 63, 3576, 18, 15330, 65, 273, 4624, 2531, 1972, 63, 3576, 18, 15330, 15533, 203, 3639, 289, 203, 203, 3639, 4624, 2531, 1972, 63, 3576, 18, 15330, 65, 273, 460, 31, 203, 203, 3639, 3626, 1000, 6763, 2531, 620, 12, 3576, 18, 15330, 16, 460, 16, 4624, 2531, 10694, 63, 3576, 18, 15330, 19226, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./abstracts/OwnableProxyDelegation.sol"; import "./abstracts/MixinOperatorResolver.sol"; import "./libraries/ExchangeHelpers.sol"; import "./interfaces/external/IWETH.sol"; import "./interfaces/INestedFactory.sol"; import "./FeeSplitter.sol"; import "./NestedReserve.sol"; import "./NestedAsset.sol"; import "./NestedRecords.sol"; import "./Withdrawer.sol"; import "hardhat/console.sol"; /// @title Creates, updates and destroys NestedAssets (portfolios). /// @notice Responsible for the business logic of the protocol and interaction with operators contract NestedFactory is INestedFactory, ReentrancyGuard, OwnableProxyDelegation, MixinOperatorResolver { /* ----------------------------- VARIABLES ----------------------------- */ address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Supported operators by the factory contract bytes32[] private operators; /// @dev Current feeSplitter contract/address FeeSplitter public feeSplitter; /// @dev Current reserve contract/address NestedReserve public immutable reserve; /// @dev Current nested asset (ERC721) contract/address NestedAsset public immutable nestedAsset; /// @dev Wrapped Ether contract/address /// Note: Will be WMATIC, WAVAX, WBNB,... Depending on the chain. IWETH public immutable weth; /// @dev Current records contract/address NestedRecords public immutable nestedRecords; /// @dev Helper to withdraw native tokens from wrapper Withdrawer private immutable withdrawer; /// @dev Fees when funds stay in portfolios /// From 1 to 10,000 (0.01% to 100%) uint256 public entryFees; /// @dev Fees when funds are withdrawed /// From 1 to 10,000 (0.01% to 100%) uint256 public exitFees; /* ---------------------------- CONSTRUCTOR ---------------------------- */ constructor( NestedAsset _nestedAsset, NestedRecords _nestedRecords, NestedReserve _reserve, FeeSplitter _feeSplitter, IWETH _weth, address _operatorResolver, Withdrawer _withdrawer ) MixinOperatorResolver(_operatorResolver) { require( address(_nestedAsset) != address(0) && address(_nestedRecords) != address(0) && address(_reserve) != address(0) && address(_feeSplitter) != address(0) && address(_weth) != address(0) && _operatorResolver != address(0) && address(_withdrawer) != address(0), "NF: INVALID_ADDRESS" ); nestedAsset = _nestedAsset; nestedRecords = _nestedRecords; reserve = _reserve; feeSplitter = _feeSplitter; weth = _weth; withdrawer = _withdrawer; } /// @dev Receive function receive() external payable { require(msg.sender == address(withdrawer), "NF: ETH_SENDER_NOT_WITHDRAWER"); } /* ------------------------------ MODIFIERS ---------------------------- */ /// @dev Reverts the transaction if the caller is not the token owner /// @param _nftId The NFT Id modifier onlyTokenOwner(uint256 _nftId) { require(nestedAsset.ownerOf(_nftId) == _msgSender(), "NF: CALLER_NOT_OWNER"); _; } /// @dev Reverts the transaction if the nft is locked (hold by design). /// The block.timestamp must be greater than NFT record lock timestamp /// @param _nftId The NFT Id modifier isUnlocked(uint256 _nftId) { require(block.timestamp > nestedRecords.getLockTimestamp(_nftId), "NF: LOCKED_NFT"); _; } /* ------------------------------- VIEWS ------------------------------- */ /// @notice Get the required operators function resolverOperatorsRequired() public view override returns (bytes32[] memory) { return operators; } /* -------------------------- OWNER FUNCTIONS -------------------------- */ /// @inheritdoc INestedFactory function addOperator(bytes32 operator) external override onlyOwner { require(operator != bytes32(""), "NF: INVALID_OPERATOR_NAME"); bytes32[] memory operatorsCache = operators; for (uint256 i = 0; i < operatorsCache.length; i++) { require(operatorsCache[i] != operator, "NF: EXISTENT_OPERATOR"); } operators.push(operator); rebuildCache(); emit OperatorAdded(operator); } /// @inheritdoc INestedFactory function removeOperator(bytes32 operator) external override onlyOwner { bytes32[] storage operatorsCache = operators; uint256 operatorsLength = operatorsCache.length; for (uint256 i = 0; i < operatorsLength; i++) { if (operatorsCache[i] == operator) { operatorsCache[i] = operators[operatorsLength - 1]; operatorsCache.pop(); if (operatorCache[operator].implementation != address(0)) { delete operatorCache[operator]; // remove from cache } rebuildCache(); emit OperatorRemoved(operator); return; } } revert("NF: NON_EXISTENT_OPERATOR"); } /// @inheritdoc INestedFactory function setFeeSplitter(FeeSplitter _feeSplitter) external override onlyOwner { require(address(_feeSplitter) != address(0), "NF: INVALID_FEE_SPLITTER_ADDRESS"); feeSplitter = _feeSplitter; emit FeeSplitterUpdated(address(_feeSplitter)); } /// @inheritdoc INestedFactory function setEntryFees(uint256 _entryFees) external override onlyOwner { require(_entryFees != 0, "NF: ZERO_FEES"); require(_entryFees <= 10000, "NF: FEES_OVERFLOW"); entryFees = _entryFees; emit EntryFeesUpdated(_entryFees); } /// @inheritdoc INestedFactory function setExitFees(uint256 _exitFees) external override onlyOwner { require(_exitFees != 0, "NF: ZERO_FEES"); require(_exitFees <= 10000, "NF: FEES_OVERFLOW"); exitFees = _exitFees; emit ExitFeesUpdated(_exitFees); } /// @inheritdoc INestedFactory function unlockTokens(IERC20 _token) external override onlyOwner { uint256 amount = _token.balanceOf(address(this)); SafeERC20.safeTransfer(_token, msg.sender, amount); emit TokensUnlocked(address(_token), amount); } /* -------------------------- USERS FUNCTIONS -------------------------- */ /// @inheritdoc INestedFactory function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders) external payable override nonReentrant { uint256 batchedOrdersLength = _batchedOrders.length; require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS"); _checkMsgValue(_batchedOrders); uint256 nftId = nestedAsset.mint(_msgSender(), _originalTokenId); for (uint256 i = 0; i < batchedOrdersLength; i++) { (uint256 fees, IERC20 tokenSold) = _submitInOrders(nftId, _batchedOrders[i], false); _transferFeeWithRoyalty(fees, tokenSold, nftId); } emit NftCreated(nftId, _originalTokenId); } /// @inheritdoc INestedFactory function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) external payable override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) { _checkMsgValue(_batchedOrders); _processInputOrders(_nftId, _batchedOrders); emit NftUpdated(_nftId); } /// @inheritdoc INestedFactory function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) { _processOutputOrders(_nftId, _batchedOrders); emit NftUpdated(_nftId); } /// @inheritdoc INestedFactory function processInputAndOutputOrders( uint256 _nftId, BatchedInputOrders[] calldata _batchedInputOrders, BatchedOutputOrders[] calldata _batchedOutputOrders ) external payable override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) { _checkMsgValue(_batchedInputOrders); _processInputOrders(_nftId, _batchedInputOrders); _processOutputOrders(_nftId, _batchedOutputOrders); emit NftUpdated(_nftId); } /// @inheritdoc INestedFactory function destroy( uint256 _nftId, IERC20 _buyToken, Order[] calldata _orders ) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) { address[] memory tokens = nestedRecords.getAssetTokens(_nftId); uint256 tokensLength = tokens.length; require(_orders.length != 0, "NF: INVALID_ORDERS"); require(tokensLength == _orders.length, "NF: INPUTS_LENGTH_MUST_MATCH"); require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH"); uint256 buyTokenInitialBalance = _buyToken.balanceOf(address(this)); for (uint256 i = 0; i < tokensLength; i++) { address token = tokens[i]; uint256 amount = _safeWithdraw(token, _nftId); _safeSubmitOrder(token, address(_buyToken), amount, _nftId, _orders[i]); } // Amount calculation to send fees and tokens uint256 amountBought = _buyToken.balanceOf(address(this)) - buyTokenInitialBalance; uint256 amountFees = (amountBought * exitFees) / 10000; // Exit Fees unchecked { amountBought -= amountFees; _transferFeeWithRoyalty(amountFees, _buyToken, _nftId); _safeTransferAndUnwrap(_buyToken, amountBought, _msgSender()); } // Burn NFT nestedRecords.removeNFT(_nftId); nestedAsset.burn(_msgSender(), _nftId); } /// @inheritdoc INestedFactory function withdraw(uint256 _nftId, uint256 _tokenIndex) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) { uint256 assetTokensLength = nestedRecords.getAssetTokensLength(_nftId); require(assetTokensLength > _tokenIndex, "NF: INVALID_TOKEN_INDEX"); // Use destroy instead if NFT has a single holding require(assetTokensLength > 1, "NF: UNALLOWED_EMPTY_PORTFOLIO"); require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH"); address token = nestedRecords.getAssetTokens(_nftId)[_tokenIndex]; uint256 amount = _safeWithdraw(token, _nftId); _safeTransferWithFees(IERC20(token), amount, _msgSender(), _nftId); nestedRecords.deleteAsset(_nftId, _tokenIndex); emit NftUpdated(_nftId); } /// @inheritdoc INestedFactory function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external override onlyTokenOwner(_nftId) { nestedRecords.updateLockTimestamp(_nftId, _timestamp); } /* ------------------------- PRIVATE FUNCTIONS ------------------------- */ /// @dev Internal logic extraction of processInputOrders() /// @param _nftId The id of the NFT to update /// @param _batchedOrders The order to execute function _processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) private { uint256 batchedOrdersLength = _batchedOrders.length; require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS"); require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH"); for (uint256 i = 0; i < batchedOrdersLength; i++) { (uint256 fees, IERC20 tokenSold) = _submitInOrders( _nftId, _batchedOrders[i], _batchedOrders[i].fromReserve ); _transferFeeWithRoyalty(fees, tokenSold, _nftId); } } /// @dev Internal logic extraction of processOutputOrders() /// @param _nftId The id of the NFT to update /// @param _batchedOrders The order to execute function _processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) private { uint256 batchedOrdersLength = _batchedOrders.length; require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS"); require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH"); for (uint256 i = 0; i < batchedOrdersLength; i++) { (uint256 feesAmount, uint256 amountBought) = _submitOutOrders( _nftId, _batchedOrders[i], _batchedOrders[i].toReserve ); _transferFeeWithRoyalty(feesAmount, _batchedOrders[i].outputToken, _nftId); if (!_batchedOrders[i].toReserve) { _safeTransferAndUnwrap(_batchedOrders[i].outputToken, amountBought - feesAmount, _msgSender()); } } } /// @dev For every orders, call the operator with the calldata /// to submit orders (where the input is one asset). /// @param _nftId The id of the NFT impacted by the orders /// @param _batchedOrders The order to process /// @param _fromReserve True if the input tokens are from the reserve (portfolio) /// @return feesAmount The total amount of fees on the input /// @return tokenSold The ERC20 token sold (in case of ETH to WETH) function _submitInOrders( uint256 _nftId, BatchedInputOrders calldata _batchedOrders, bool _fromReserve ) private returns (uint256 feesAmount, IERC20 tokenSold) { uint256 batchLength = _batchedOrders.orders.length; require(batchLength != 0, "NF: INVALID_ORDERS"); uint256 _inputTokenAmount; (tokenSold, _inputTokenAmount) = _transferInputTokens( _nftId, _batchedOrders.inputToken, _batchedOrders.amount, _fromReserve ); uint256 amountSpent; for (uint256 i = 0; i < batchLength; i++) { amountSpent += _submitOrder( address(tokenSold), _batchedOrders.orders[i].token, _nftId, _batchedOrders.orders[i], true // always to the reserve ); } feesAmount = (amountSpent * entryFees) / 10000; // Entry Fees require(amountSpent <= _inputTokenAmount - feesAmount, "NF: OVERSPENT"); unchecked { uint256 underSpentAmount = _inputTokenAmount - feesAmount - amountSpent; if (underSpentAmount != 0) { SafeERC20.safeTransfer(tokenSold, _fromReserve ? address(reserve) : _msgSender(), underSpentAmount); } // If input is from the reserve, update the records if (_fromReserve) { _decreaseHoldingAmount(_nftId, address(tokenSold), _inputTokenAmount - underSpentAmount); } } } /// @dev For every orders, call the operator with the calldata /// to submit sell orders (where the output is one asset). /// @param _nftId The id of the NFT impacted by the orders /// @param _batchedOrders The order to process /// @param _toReserve True if the output is store in the reserve/records (portfolio), false if not. /// @return feesAmount The total amount of fees on the output /// @return amountBought The total amount bought function _submitOutOrders( uint256 _nftId, BatchedOutputOrders calldata _batchedOrders, bool _toReserve ) private returns (uint256 feesAmount, uint256 amountBought) { uint256 batchLength = _batchedOrders.orders.length; require(batchLength != 0, "NF: INVALID_ORDERS"); require(_batchedOrders.amounts.length == batchLength, "NF: INPUTS_LENGTH_MUST_MATCH"); amountBought = _batchedOrders.outputToken.balanceOf(address(this)); IERC20 _inputToken; uint256 _inputTokenAmount; for (uint256 i = 0; i < batchLength; i++) { (_inputToken, _inputTokenAmount) = _transferInputTokens( _nftId, IERC20(_batchedOrders.orders[i].token), _batchedOrders.amounts[i], true ); // Submit order and update holding of spent token uint256 amountSpent = _submitOrder( address(_inputToken), address(_batchedOrders.outputToken), _nftId, _batchedOrders.orders[i], false ); require(amountSpent <= _inputTokenAmount, "NF: OVERSPENT"); unchecked { uint256 underSpentAmount = _inputTokenAmount - amountSpent; if (underSpentAmount != 0) { SafeERC20.safeTransfer(_inputToken, address(reserve), underSpentAmount); } _decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmount - underSpentAmount); } } amountBought = _batchedOrders.outputToken.balanceOf(address(this)) - amountBought; unchecked { // Entry or Exit Fees feesAmount = (amountBought * (_toReserve ? entryFees : exitFees)) / 10000; if (_toReserve) { _transferToReserveAndStore(_batchedOrders.outputToken, amountBought - feesAmount, _nftId); } } } /// @dev Call the operator to submit the order and add the output /// assets to the reserve (if needed). /// @param _inputToken Token used to make the orders /// @param _outputToken Expected output token /// @param _nftId The nftId /// @param _order The order calldata /// @param _toReserve True if the output is store in the reserve/records, false if not. /// @return amountSpent The _inputToken amount spent (with the order) function _submitOrder( address _inputToken, address _outputToken, uint256 _nftId, Order calldata _order, bool _toReserve ) private returns (uint256 amountSpent) { (bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken); require(success, "NF: OPERATOR_CALL_FAILED"); if (_toReserve) { _transferToReserveAndStore(IERC20(_outputToken), amounts[0], _nftId); } amountSpent = amounts[1]; } /// @dev Call the operator to submit the order but dont stop if the call to the operator fail. /// It will send the input token back to the msg.sender. /// Note : The _toReserve Boolean has been removed (compare to _submitOrder) since it was /// useless for the only use case (destroy). /// @param _inputToken Token used to make the orders /// @param _outputToken Expected output token /// @param _amountToSpend The input amount available (to spend) /// @param _nftId The nftId /// @param _order The order calldata function _safeSubmitOrder( address _inputToken, address _outputToken, uint256 _amountToSpend, uint256 _nftId, Order calldata _order ) private { (bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken); if (success) { require(amounts[1] <= _amountToSpend, "NF: OVERSPENT"); unchecked { uint256 underSpentAmount = _amountToSpend - amounts[1]; if (underSpentAmount != 0) { SafeERC20.safeTransfer(IERC20(_inputToken), _msgSender(), underSpentAmount); } } } else { _safeTransferWithFees(IERC20(_inputToken), _amountToSpend, _msgSender(), _nftId); } } /// @dev Transfer tokens to the reserve, and compute the amount received to store /// in the records. We need to know the amount received in case of deflationary tokens. /// @param _token The token to transfer (IERC20) /// @param _amount The amount to send to the reserve /// @param _nftId The Token ID to store the assets function _transferToReserveAndStore( IERC20 _token, uint256 _amount, uint256 _nftId ) private { address reserveAddr = address(reserve); uint256 balanceReserveBefore = _token.balanceOf(reserveAddr); // Send output to reserve SafeERC20.safeTransfer(_token, reserveAddr, _amount); uint256 balanceReserveAfter = _token.balanceOf(reserveAddr); nestedRecords.store(_nftId, address(_token), balanceReserveAfter - balanceReserveBefore, reserveAddr); } /// @dev Choose between ERC20 (safeTransfer) and ETH (deposit), to transfer from the Reserve /// or the user wallet, to the factory. /// @param _nftId The NFT id /// @param _inputToken The token to receive /// @param _inputTokenAmount Amount to transfer /// @param _fromReserve True to transfer from the reserve /// @return Token transfered (in case of ETH) /// @return The real amount received after the transfer to the factory function _transferInputTokens( uint256 _nftId, IERC20 _inputToken, uint256 _inputTokenAmount, bool _fromReserve ) private returns (IERC20, uint256) { if (address(_inputToken) == ETH) { require(!_fromReserve, "NF: NO_ETH_FROM_RESERVE"); require(address(this).balance >= _inputTokenAmount, "NF: INVALID_AMOUNT_IN"); weth.deposit{ value: _inputTokenAmount }(); return (IERC20(address(weth)), _inputTokenAmount); } uint256 balanceBefore = _inputToken.balanceOf(address(this)); if (_fromReserve) { require( nestedRecords.getAssetHolding(_nftId, address(_inputToken)) >= _inputTokenAmount, "NF: INSUFFICIENT_AMOUNT_IN" ); // Get input from reserve reserve.withdraw(_inputToken, _inputTokenAmount); } else { SafeERC20.safeTransferFrom(_inputToken, _msgSender(), address(this), _inputTokenAmount); } return (_inputToken, _inputToken.balanceOf(address(this)) - balanceBefore); } /// @dev Send a fee to the FeeSplitter, royalties will be paid to the owner of the original asset /// @param _amount Amount to send /// @param _token Token to send /// @param _nftId User portfolio ID used to find a potential royalties recipient function _transferFeeWithRoyalty( uint256 _amount, IERC20 _token, uint256 _nftId ) private { address originalOwner = nestedAsset.originalOwner(_nftId); ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter)); if (originalOwner != address(0)) { feeSplitter.sendFeesWithRoyalties(originalOwner, _token, _amount); } else { feeSplitter.sendFees(_token, _amount); } } /// @dev Decrease the amount of a NFT holding /// @param _nftId The NFT id /// @param _inputToken The token holding /// @param _amount The amount to subtract from the actual holding amount function _decreaseHoldingAmount( uint256 _nftId, address _inputToken, uint256 _amount ) private { nestedRecords.updateHoldingAmount( _nftId, _inputToken, nestedRecords.getAssetHolding(_nftId, _inputToken) - _amount ); } /// @dev Transfer a token amount from the factory to the recipient. /// The token is unwrapped if WETH. /// @param _token The token to transfer /// @param _amount The amount to transfer /// @param _dest The address receiving the funds function _safeTransferAndUnwrap( IERC20 _token, uint256 _amount, address _dest ) private { // if buy token is WETH, unwrap it instead of transferring it to the sender if (address(_token) == address(weth)) { ExchangeHelpers.setMaxAllowance(IERC20(address(weth)), address(withdrawer)); withdrawer.withdraw(_amount); (bool success, ) = _dest.call{ value: _amount }(""); require(success, "NF: ETH_TRANSFER_ERROR"); } else { SafeERC20.safeTransfer(_token, _dest, _amount); } } /// @dev Transfer from factory and collect fees /// @param _token The token to transfer /// @param _amount The amount (with fees) to transfer /// @param _dest The address receiving the funds /// @param _nftId The nft Id (for royalty fees) function _safeTransferWithFees( IERC20 _token, uint256 _amount, address _dest, uint256 _nftId ) private { uint256 feeAmount = (_amount * exitFees) / 10000; // Exit Fee unchecked { _transferFeeWithRoyalty(feeAmount, _token, _nftId); SafeERC20.safeTransfer(_token, _dest, _amount - feeAmount); } } /// @dev Withdraw from reserve with care of deflationary tokens. /// @param _token The token to withdraw /// @param _nftId The NFT id to withdraw from /// @return The withdrawed amount from the reserve function _safeWithdraw(address _token, uint256 _nftId) private returns (uint256) { uint256 holdingAmount = nestedRecords.getAssetHolding(_nftId, _token); uint256 balanceBefore = IERC20(_token).balanceOf(address(this)); reserve.withdraw(IERC20(_token), holdingAmount); return IERC20(_token).balanceOf(address(this)) - balanceBefore; } /// @dev Verify that msg.value is equal to the amount needed (in the orders) /// @param _batchedOrders The batched input orders function _checkMsgValue(BatchedInputOrders[] calldata _batchedOrders) private { uint256 ethNeeded; for (uint256 i = 0; i < _batchedOrders.length; i++) { if (address(_batchedOrders[i].inputToken) == ETH) { ethNeeded += _batchedOrders[i].amount; } } require(msg.value == ethNeeded, "NF: WRONG_MSG_VALUE"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/StorageSlot.sol"; /// @notice Ownable re-implementation to initialize the owner in the /// proxy storage after an "upgradeToAndCall()" (delegatecall). /// @dev The implementation contract owner will be address zero (by removing the constructor) abstract contract OwnableProxyDelegation is Context { /// @dev The contract owner address private _owner; /// @dev Storage slot with the proxy admin (see TransparentUpgradeableProxy from OZ) bytes32 internal constant _ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1); /// @dev True if the owner is setted bool public initialized; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Initialize the owner (by the proxy admin) /// @param ownerAddr The owner address function initialize(address ownerAddr) external { require(ownerAddr != address(0), "OPD: INVALID_ADDRESS"); require(!initialized, "OPD: INITIALIZED"); require(StorageSlot.getAddressSlot(_ADMIN_SLOT).value == msg.sender, "OPD: FORBIDDEN"); _setOwner(ownerAddr); initialized = true; } /// @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(), "OPD: NOT_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), "OPD: INVALID_ADDRESS"); _setOwner(newOwner); } /// @dev Update the owner address /// @param newOwner The new owner address function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "../OperatorResolver.sol"; import "../interfaces/IOperatorResolver.sol"; import "../interfaces/INestedFactory.sol"; /// @title Mixin operator resolver /// @notice Store in cache operators name and address/selector abstract contract MixinOperatorResolver { /// @notice Emitted when cache is updated /// @param name The operator name /// @param destination The operator address event CacheUpdated(bytes32 name, IOperatorResolver.Operator destination); /// @dev The OperatorResolver used to build the cache OperatorResolver public immutable resolver; /// @dev Cache operators map of the name and Operator struct (address/selector) mapping(bytes32 => IOperatorResolver.Operator) internal operatorCache; constructor(address _resolver) { require(_resolver != address(0), "MOR: INVALID_ADDRESS"); resolver = OperatorResolver(_resolver); } /// @dev This function is public not external in order for it to be overridden and /// invoked via super in subclasses function resolverOperatorsRequired() public view virtual returns (bytes32[] memory) {} /// @notice Rebuild the operatorCache function rebuildCache() public { bytes32[] memory requiredOperators = resolverOperatorsRequired(); bytes32 name; IOperatorResolver.Operator memory destination; // The resolver must call this function whenever it updates its state for (uint256 i = 0; i < requiredOperators.length; i++) { name = requiredOperators[i]; // Note: can only be invoked once the resolver has all the targets needed added destination = resolver.getOperator(name); if (destination.implementation != address(0)) { operatorCache[name] = destination; } else { delete operatorCache[name]; } emit CacheUpdated(name, destination); } } /// @notice Check the state of operatorCache function isResolverCached() external view returns (bool) { bytes32[] memory requiredOperators = resolverOperatorsRequired(); bytes32 name; IOperatorResolver.Operator memory cacheTmp; IOperatorResolver.Operator memory actualValue; for (uint256 i = 0; i < requiredOperators.length; i++) { name = requiredOperators[i]; cacheTmp = operatorCache[name]; actualValue = resolver.getOperator(name); // false if our cache is invalid or if the resolver doesn't have the required address if ( actualValue.implementation != cacheTmp.implementation || actualValue.selector != cacheTmp.selector || cacheTmp.implementation == address(0) ) { return false; } } return true; } /// @dev Get operator address in cache and require (if exists) /// @param name The operator name /// @return The operator address function requireAndGetAddress(bytes32 name) internal view returns (IOperatorResolver.Operator memory) { IOperatorResolver.Operator memory _foundAddress = operatorCache[name]; require(_foundAddress.implementation != address(0), string(abi.encodePacked("MOR: MISSING_OPERATOR: ", name))); return _foundAddress; } /// @dev Build the calldata (with safe datas) and call the Operator /// @param _order The order to execute /// @param _inputToken The input token address /// @param _outputToken The output token address /// @return success If the operator call is successful /// @return amounts The amounts from the execution (used and received) /// - amounts[0] : The amount of output token /// - amounts[1] : The amount of input token USED by the operator (can be different than expected) function callOperator( INestedFactory.Order calldata _order, address _inputToken, address _outputToken ) internal returns (bool success, uint256[] memory amounts) { IOperatorResolver.Operator memory _operator = requireAndGetAddress(_order.operator); // Parameters are concatenated and padded to 32 bytes. // We are concatenating the selector + given params bytes memory data; (success, data) = _operator.implementation.delegatecall(bytes.concat(_operator.selector, _order.callData)); if (success) { address[] memory tokens; (amounts, tokens) = abi.decode(data, (uint256[], address[])); require(tokens[0] == _outputToken, "MOR: INVALID_OUTPUT_TOKEN"); require(tokens[1] == _inputToken, "MOR: INVALID_INPUT_TOKEN"); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @notice Helpers for swapping tokens library ExchangeHelpers { using SafeERC20 for IERC20; /// @dev Perform a swap between two tokens /// @param _sellToken Token to exchange /// @param _swapTarget The address of the contract that swaps tokens /// @param _swapCallData Call data provided by 0x to fill the quote /// @return True if the call succeeded, false if not function fillQuote( IERC20 _sellToken, address _swapTarget, bytes memory _swapCallData ) internal returns (bool) { setMaxAllowance(_sellToken, _swapTarget); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = _swapTarget.call(_swapCallData); return success; } /// @dev sets the allowance for a token to the maximum if it is not already at max /// @param _token The token to use for the allowance setting /// @param _spender Spender to allow function setMaxAllowance(IERC20 _token, address _spender) internal { uint256 _currentAllowance = _token.allowance(address(this), _spender); if (_currentAllowance != type(uint256).max) { // Decrease to 0 first for tokens mitigating the race condition _token.safeDecreaseAllowance(_spender, _currentAllowance); _token.safeIncreaseAllowance(_spender, type(uint256).max); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.11; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function totalSupply() 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); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../NestedReserve.sol"; import "../FeeSplitter.sol"; /// @title NestedFactory interface interface INestedFactory { /* ------------------------------ EVENTS ------------------------------ */ /// @dev Emitted when the feeSplitter is updated /// @param feeSplitter The new feeSplitter address event FeeSplitterUpdated(address feeSplitter); /// @dev Emitted when the entryFees is updated /// @param entryFees The new entryFees amount event EntryFeesUpdated(uint256 entryFees); /// @dev Emitted when the exitFees is updated /// @param exitFees The new exitFees amount event ExitFeesUpdated(uint256 exitFees); /// @dev Emitted when the reserve is updated /// @param reserve The new reserve address event ReserveUpdated(address reserve); /// @dev Emitted when a NFT (portfolio) is created /// @param nftId The NFT token Id /// @param originalNftId If replicated, the original NFT token Id event NftCreated(uint256 indexed nftId, uint256 originalNftId); /// @dev Emitted when a NFT (portfolio) is updated /// @param nftId The NFT token Id event NftUpdated(uint256 indexed nftId); /// @dev Emitted when a new operator is added /// @param newOperator The new operator bytes name event OperatorAdded(bytes32 newOperator); /// @dev Emitted when an operator is removed /// @param oldOperator The old operator bytes name event OperatorRemoved(bytes32 oldOperator); /// @dev Emitted when tokens are unlocked (sent to the owner) /// @param token The unlocked token address /// @param amount The unlocked amount event TokensUnlocked(address token, uint256 amount); /* ------------------------------ STRUCTS ------------------------------ */ /// @dev Represent an order made to the factory when creating/editing an NFT /// @param operator The bytes32 name of the Operator /// @param token The expected token address in output/input /// @param callData The operator parameters (delegatecall) struct Order { bytes32 operator; address token; bytes callData; } /// @dev Represent multiple input orders for a given token to perform multiple trades. /// @param inputToken The input token /// @param amount The amount to transfer (input amount) /// @param orders The orders to perform using the input token. /// @param _fromReserve Specify the input token source (true if reserve, false if wallet) /// Note: fromReserve can be read as "from portfolio" struct BatchedInputOrders { IERC20 inputToken; uint256 amount; Order[] orders; bool fromReserve; } /// @dev Represent multiple output orders to receive a given token /// @param outputToken The output token /// @param amounts The amount of sell tokens to use /// @param orders Orders calldata /// @param toReserve Specify the output token destination (true if reserve, false if wallet) /// Note: toReserve can be read as "to portfolio" struct BatchedOutputOrders { IERC20 outputToken; uint256[] amounts; Order[] orders; bool toReserve; } /* ------------------------------ OWNER FUNCTIONS ------------------------------ */ /// @notice Add an operator (name) for building cache /// @param operator The operator name to add function addOperator(bytes32 operator) external; /// @notice Remove an operator (name) for building cache /// @param operator The operator name to remove function removeOperator(bytes32 operator) external; /// @notice Sets the address receiving the fees /// @param _feeSplitter The address of the receiver function setFeeSplitter(FeeSplitter _feeSplitter) external; /// @notice Sets the entry fees amount /// Where 1 = 0.01% and 10000 = 100% /// @param _entryFees Entry fees amount function setEntryFees(uint256 _entryFees) external; /// @notice Sets the exit fees amount /// Where 1 = 0.01% and 10000 = 100% /// @param _exitFees Exit fees amount function setExitFees(uint256 _exitFees) external; /// @notice The Factory is not storing funds, but some users can make /// bad manipulations and send tokens to the contract. /// In response to that, the owner can retrieve the factory balance of a given token /// to later return users funds. /// @param _token The token to retrieve. function unlockTokens(IERC20 _token) external; /* ------------------------------ USERS FUNCTIONS ------------------------------ */ /// @notice Create a portfolio and store the underlying assets from the positions /// @param _originalTokenId The id of the NFT replicated, 0 if not replicating /// @param _batchedOrders The order to execute function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders) external payable; /// @notice Process multiple input orders /// @param _nftId The id of the NFT to update /// @param _batchedOrders The order to execute function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) external payable; /// @notice Process multiple output orders /// @param _nftId The id of the NFT to update /// @param _batchedOrders The order to execute function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external; /// @notice Process multiple input orders and then multiple output orders /// @param _nftId The id of the NFT to update /// @param _batchedInputOrders The input orders to execute (first) /// @param _batchedOutputOrders The output orders to execute (after) function processInputAndOutputOrders( uint256 _nftId, BatchedInputOrders[] calldata _batchedInputOrders, BatchedOutputOrders[] calldata _batchedOutputOrders ) external payable; /// @notice Burn NFT and exchange all tokens for a specific ERC20 then send it back to the user /// @dev Will unwrap WETH output to ETH /// @param _nftId The id of the NFT to destroy /// @param _buyToken The output token /// @param _orders Orders calldata function destroy( uint256 _nftId, IERC20 _buyToken, Order[] calldata _orders ) external; /// @notice Withdraw a token from the reserve and transfer it to the owner without exchanging it /// @param _nftId NFT token ID /// @param _tokenIndex Index in array of tokens for this NFT and holding. function withdraw(uint256 _nftId, uint256 _tokenIndex) external; /// @notice Update the lock timestamp of an NFT record. /// Note: Can only increase the lock timestamp. /// @param _nftId The NFT id to get the record /// @param _timestamp The new timestamp. function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/external/IWETH.sol"; /// @title Manage the fees between shareholders /// @notice Receives fees collected by the NestedFactory, and splits the income among /// shareholders (the NFT owners, Nested treasury and a NST buybacker contract). contract FeeSplitter is Ownable, ReentrancyGuard { /* ------------------------------ EVENTS ------------------------------ */ /// @dev Emitted when a payment is released /// @param to The address receiving the payment /// @param token The token transfered /// @param amount The amount paid event PaymentReleased(address to, address token, uint256 amount); /// @dev Emitted when a payment is received /// @param from The address sending the tokens /// @param token The token received /// @param amount The amount received event PaymentReceived(address from, address token, uint256 amount); /// @dev Emitted when the royalties weight is updated /// @param weight The new weight event RoyaltiesWeightUpdated(uint256 weight); /// @dev Emitted when a new shareholder is added /// @param account The new shareholder account /// @param weight The shareholder weight event ShareholdersAdded(address account, uint256 weight); /// @dev Emitted when a shareholder weight is updated /// @param account The shareholder address /// @param weight The new weight event ShareholderUpdated(address account, uint256 weight); /// @dev Emitted when royalties are claim released /// @param to The address claiming the royalties /// @param token The token received /// @param value The amount received event RoyaltiesReceived(address to, address token, uint256 value); /* ------------------------------ STRUCTS ------------------------------ */ /// @dev Represent a shareholder /// @param account Shareholders address that can receive income /// @param weight Determines share allocation struct Shareholder { address account; uint96 weight; } /// @dev Registers shares and amount release for a specific token or ETH struct TokenRecords { uint256 totalShares; uint256 totalReleased; mapping(address => uint256) shares; mapping(address => uint256) released; } /* ----------------------------- VARIABLES ----------------------------- */ /// @dev Map of tokens with the tokenRecords mapping(address => TokenRecords) private tokenRecords; /// @dev All the shareholders (array) Shareholder[] private shareholders; /// @dev Royalties part weights when applicable uint256 public royaltiesWeight; uint256 public totalWeights; address public immutable weth; /* ---------------------------- CONSTRUCTOR ---------------------------- */ constructor( address[] memory _accounts, uint96[] memory _weights, uint256 _royaltiesWeight, address _weth ) { require(_weth != address(0), "FS: INVALID_ADDRESS"); // Initial shareholders addresses and weights setShareholders(_accounts, _weights); setRoyaltiesWeight(_royaltiesWeight); weth = _weth; } /// @dev Receive ether after a WETH withdraw call receive() external payable { require(msg.sender == weth, "FS: ETH_SENDER_NOT_WETH"); } /* -------------------------- OWNER FUNCTIONS -------------------------- */ /// @notice Sets the weight assigned to the royalties part for the fee /// @param _weight The new royalties weight function setRoyaltiesWeight(uint256 _weight) public onlyOwner { require(_weight != 0, "FS: WEIGHT_ZERO"); totalWeights = totalWeights + _weight - royaltiesWeight; royaltiesWeight = _weight; emit RoyaltiesWeightUpdated(_weight); } /// @notice Sets a new list of shareholders /// @param _accounts Shareholders accounts list /// @param _weights Weight for each shareholder. Determines part of the payment allocated to them function setShareholders(address[] memory _accounts, uint96[] memory _weights) public onlyOwner { delete shareholders; uint256 accountsLength = _accounts.length; require(accountsLength != 0, "FS: EMPTY_ARRAY"); require(accountsLength == _weights.length, "FS: INPUTS_LENGTH_MUST_MATCH"); totalWeights = royaltiesWeight; for (uint256 i = 0; i < accountsLength; i++) { _addShareholder(_accounts[i], _weights[i]); } } /// @notice Updates weight for a shareholder /// @param _accountIndex Account to change the weight of /// @param _weight The new weight function updateShareholder(uint256 _accountIndex, uint96 _weight) external onlyOwner { require(_weight != 0, "FS: INVALID_WEIGHT"); require(_accountIndex < shareholders.length, "FS: INVALID_ACCOUNT_INDEX"); Shareholder storage _shareholder = shareholders[_accountIndex]; totalWeights = totalWeights + _weight - _shareholder.weight; require(totalWeights != 0, "FS: TOTAL_WEIGHTS_ZERO"); _shareholder.weight = _weight; emit ShareholderUpdated(_shareholder.account, _weight); } /* -------------------------- USERS FUNCTIONS -------------------------- */ /// @notice Release multiple tokens and handle ETH unwrapping /// @param _tokens ERC20 tokens to release function releaseTokens(IERC20[] calldata _tokens) external nonReentrant { uint256 amount; for (uint256 i = 0; i < _tokens.length; i++) { amount = _releaseToken(_msgSender(), _tokens[i]); if (address(_tokens[i]) == weth) { IWETH(weth).withdraw(amount); (bool success, ) = _msgSender().call{ value: amount }(""); require(success, "FS: ETH_TRANFER_ERROR"); } else { SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount); } emit PaymentReleased(_msgSender(), address(_tokens[i]), amount); } } /// @notice Release multiple tokens without ETH unwrapping /// @param _tokens ERC20 tokens to release function releaseTokensNoETH(IERC20[] calldata _tokens) external nonReentrant { uint256 amount; for (uint256 i = 0; i < _tokens.length; i++) { amount = _releaseToken(_msgSender(), _tokens[i]); SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount); emit PaymentReleased(_msgSender(), address(_tokens[i]), amount); } } /// @notice Sends a fee to this contract for splitting, as an ERC20 token. No royalties are expected. /// @param _token Currency for the fee as an ERC20 token /// @param _amount Amount of token as fee to be claimed by this contract function sendFees(IERC20 _token, uint256 _amount) external nonReentrant { uint256 weights; unchecked { weights = totalWeights - royaltiesWeight; } uint256 balanceBeforeTransfer = _token.balanceOf(address(this)); SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount); _sendFees(_token, _token.balanceOf(address(this)) - balanceBeforeTransfer, weights); } /// @notice Sends a fee to this contract for splitting, as an ERC20 token /// @param _royaltiesTarget The account that can claim royalties /// @param _token Currency for the fee as an ERC20 token /// @param _amount Amount of token as fee to be claimed by this contract function sendFeesWithRoyalties( address _royaltiesTarget, IERC20 _token, uint256 _amount ) external nonReentrant { require(_royaltiesTarget != address(0), "FS: INVALID_ROYALTIES_TARGET"); uint256 balanceBeforeTransfer = _token.balanceOf(address(this)); SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount); uint256 amountReceived = _token.balanceOf(address(this)) - balanceBeforeTransfer; uint256 _totalWeights = totalWeights; uint256 royaltiesAmount = (amountReceived * royaltiesWeight) / _totalWeights; _sendFees(_token, amountReceived, _totalWeights); _addShares(_royaltiesTarget, royaltiesAmount, address(_token)); emit RoyaltiesReceived(_royaltiesTarget, address(_token), royaltiesAmount); } /* ------------------------------- VIEWS ------------------------------- */ /// @notice Returns the amount due to an account. Call releaseToken to withdraw the amount. /// @param _account Account address to check the amount due for /// @param _token ERC20 payment token address /// @return The total amount due for the requested currency function getAmountDue(address _account, IERC20 _token) public view returns (uint256) { TokenRecords storage _tokenRecords = tokenRecords[address(_token)]; uint256 _totalShares = _tokenRecords.totalShares; if (_totalShares == 0) return 0; uint256 totalReceived = _tokenRecords.totalReleased + _token.balanceOf(address(this)); return (totalReceived * _tokenRecords.shares[_account]) / _totalShares - _tokenRecords.released[_account]; } /// @notice Getter for the total shares held by shareholders. /// @param _token Payment token address /// @return The total shares count function totalShares(address _token) external view returns (uint256) { return tokenRecords[_token].totalShares; } /// @notice Getter for the total amount of token already released. /// @param _token Payment token address /// @return The total amount release to shareholders function totalReleased(address _token) external view returns (uint256) { return tokenRecords[_token].totalReleased; } /// @notice Getter for the amount of shares held by an account. /// @param _account Account the shares belong to /// @param _token Payment token address /// @return The shares owned by the account function shares(address _account, address _token) external view returns (uint256) { return tokenRecords[_token].shares[_account]; } /// @notice Getter for the amount of Ether already released to a shareholders. /// @param _account The target account for this request /// @param _token Payment token address /// @return The amount already released to this account function released(address _account, address _token) external view returns (uint256) { return tokenRecords[_token].released[_account]; } /// @notice Finds a shareholder and return its index /// @param _account Account to find /// @return The shareholder index in the storage array function findShareholder(address _account) external view returns (uint256) { for (uint256 i = 0; i < shareholders.length; i++) { if (shareholders[i].account == _account) return i; } revert("FS: SHAREHOLDER_NOT_FOUND"); } /* ------------------------- PRIVATE FUNCTIONS ------------------------- */ /// @notice Transfers a fee to this contract /// @dev This method calculates the amount received, to support deflationary tokens /// @param _token Currency for the fee /// @param _amount Amount of token sent /// @param _totalWeights Total weights to determine the share count to allocate function _sendFees( IERC20 _token, uint256 _amount, uint256 _totalWeights ) private { Shareholder[] memory shareholdersCache = shareholders; for (uint256 i = 0; i < shareholdersCache.length; i++) { _addShares( shareholdersCache[i].account, (_amount * shareholdersCache[i].weight) / _totalWeights, address(_token) ); } emit PaymentReceived(_msgSender(), address(_token), _amount); } /// @dev Increase the shares of a shareholder /// @param _account The shareholder address /// @param _shares The shares of the holder /// @param _token The updated token function _addShares( address _account, uint256 _shares, address _token ) private { TokenRecords storage _tokenRecords = tokenRecords[_token]; _tokenRecords.shares[_account] += _shares; _tokenRecords.totalShares += _shares; } function _releaseToken(address _account, IERC20 _token) private returns (uint256) { uint256 amountToRelease = getAmountDue(_account, _token); require(amountToRelease != 0, "FS: NO_PAYMENT_DUE"); TokenRecords storage _tokenRecords = tokenRecords[address(_token)]; _tokenRecords.released[_account] += amountToRelease; _tokenRecords.totalReleased += amountToRelease; return amountToRelease; } function _addShareholder(address _account, uint96 _weight) private { require(_weight != 0, "FS: ZERO_WEIGHT"); require(_account != address(0), "FS: INVALID_ADDRESS"); for (uint256 i = 0; i < shareholders.length; i++) { require(shareholders[i].account != _account, "FS: ALREADY_SHAREHOLDER"); } shareholders.push(Shareholder(_account, _weight)); totalWeights += _weight; emit ShareholdersAdded(_account, _weight); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./abstracts/OwnableFactoryHandler.sol"; /// @title Stores underlying assets of NestedNFTs. /// @notice The factory itself can only trigger a transfer after verification that the user /// holds funds present in this contract. Only the factory can withdraw/transfer assets. contract NestedReserve is OwnableFactoryHandler { /// @notice Release funds to a recipient /// @param _recipient The receiver /// @param _token The token to transfer /// @param _amount The amount to transfer function transfer( address _recipient, IERC20 _token, uint256 _amount ) external onlyFactory { require(_recipient != address(0), "NRS: INVALID_ADDRESS"); SafeERC20.safeTransfer(_token, _recipient, _amount); } /// @notice Release funds to the factory /// @param _token The ERC20 to transfer /// @param _amount The amount to transfer function withdraw(IERC20 _token, uint256 _amount) external onlyFactory { SafeERC20.safeTransfer(_token, msg.sender, _amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./abstracts/OwnableFactoryHandler.sol"; /// @title Collection of NestedNFTs used to represent ownership of real assets stored in NestedReserves /// @dev Only NestedFactory contracts are allowed to call functions that write to storage contract NestedAsset is ERC721Enumerable, OwnableFactoryHandler { using Counters for Counters.Counter; /* ----------------------------- VARIABLES ----------------------------- */ Counters.Counter private _tokenIds; /// @dev Base URI (API) string public baseUri; /// @dev Token URI when not revealed string public unrevealedTokenUri; /// @dev NFT contract URI string public contractUri; /// @dev Stores the original asset of each asset mapping(uint256 => uint256) public originalAsset; /// @dev Stores owners of burnt assets mapping(uint256 => address) public lastOwnerBeforeBurn; /// @dev True if revealed, false if not. bool public isRevealed; /* ---------------------------- CONSTRUCTORS --------------------------- */ constructor() ERC721("NestedNFT", "NESTED") {} /* ----------------------------- MODIFIERS ----------------------------- */ /// @dev Reverts the transaction if the address is not the token owner modifier onlyTokenOwner(address _address, uint256 _tokenId) { require(_address == ownerOf(_tokenId), "NA: FORBIDDEN_NOT_OWNER"); _; } /* ------------------------------- VIEWS ------------------------------- */ /// @notice Get the Uniform Resource Identifier (URI) for `tokenId` token. /// @param _tokenId The id of the NestedAsset /// @return The token Uniform Resource Identifier (URI) function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token"); if (isRevealed) { return super.tokenURI(_tokenId); } else { return unrevealedTokenUri; } } /// @inheritdoc ERC721 function _baseURI() internal view override returns (string memory) { return baseUri; } /// @notice Returns the owner of the original token if the token was replicated /// If the original asset was burnt, the last owner before burn is returned /// @param _tokenId The asset for which we want to know the original owner /// @return The owner of the original asset function originalOwner(uint256 _tokenId) external view returns (address) { uint256 originalAssetId = originalAsset[_tokenId]; if (originalAssetId != 0) { return _exists(originalAssetId) ? ownerOf(originalAssetId) : lastOwnerBeforeBurn[originalAssetId]; } return address(0); } /* ---------------------------- ONLY FACTORY --------------------------- */ /// @notice Mints an ERC721 token for the user and stores the original asset used to create the new asset if any /// @param _owner The account address that signed the transaction /// @param _replicatedTokenId The token id of the replicated asset, 0 if no replication /// @return The minted token's id function mint(address _owner, uint256 _replicatedTokenId) public onlyFactory returns (uint256) { _tokenIds.increment(); uint256 tokenId = _tokenIds.current(); _safeMint(_owner, tokenId); // Stores the first asset of the replication chain as the original if (_replicatedTokenId == 0) { return tokenId; } require(_exists(_replicatedTokenId), "NA: NON_EXISTENT_TOKEN_ID"); require(tokenId != _replicatedTokenId, "NA: SELF_DUPLICATION"); uint256 originalTokenId = originalAsset[_replicatedTokenId]; originalAsset[tokenId] = originalTokenId != 0 ? originalTokenId : _replicatedTokenId; return tokenId; } /// @notice Burns an ERC721 token /// @param _owner The account address that signed the transaction /// @param _tokenId The id of the NestedAsset function burn(address _owner, uint256 _tokenId) external onlyFactory onlyTokenOwner(_owner, _tokenId) { lastOwnerBeforeBurn[_tokenId] = _owner; _burn(_tokenId); } /* ----------------------------- ONLY OWNER ---------------------------- */ /// @notice Update isRevealed to reveal or hide the token URI function setIsRevealed(bool _isRevealed) external onlyOwner { isRevealed = _isRevealed; } /// @notice Set the base URI (once revealed) /// @param _baseUri The new baseURI function setBaseURI(string memory _baseUri) external onlyOwner { require(bytes(_baseUri).length != 0, "NA: EMPTY_URI"); baseUri = _baseUri; } /// @notice Set the unrevealed token URI (fixed) /// @param _newUri The new unrevealed URI function setUnrevealedTokenURI(string memory _newUri) external onlyOwner { require(bytes(_newUri).length != 0, "NA: EMPTY_URI"); unrevealedTokenUri = _newUri; } /// @notice Set the contract URI /// @param _newUri The new contract URI function setContractURI(string memory _newUri) external onlyOwner { contractUri = _newUri; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "./abstracts/OwnableFactoryHandler.sol"; /// @title Tracks data for underlying assets of NestedNFTs contract NestedRecords is OwnableFactoryHandler { /* ------------------------------ EVENTS ------------------------------ */ /// @dev Emitted when maxHoldingsCount is updated /// @param maxHoldingsCount The new value event MaxHoldingsChanges(uint256 maxHoldingsCount); /// @dev Emitted when the lock timestamp of an NFT is increased /// @param nftId The NFT ID /// @param timestamp The new lock timestamp of the portfolio event LockTimestampIncreased(uint256 nftId, uint256 timestamp); /// @dev Emitted when the reserve is updated for a specific portfolio /// @param nftId The NFT ID /// @param newReserve The new reserve address event ReserveUpdated(uint256 nftId, address newReserve); /* ------------------------------ STRUCTS ------------------------------ */ /// @dev Store user asset informations struct NftRecord { mapping(address => uint256) holdings; address[] tokens; address reserve; uint256 lockTimestamp; } /* ----------------------------- VARIABLES ----------------------------- */ /// @dev stores for each NFT ID an asset record mapping(uint256 => NftRecord) public records; /// @dev The maximum number of holdings for an NFT record uint256 public maxHoldingsCount; /* ---------------------------- CONSTRUCTOR ---------------------------- */ constructor(uint256 _maxHoldingsCount) { maxHoldingsCount = _maxHoldingsCount; } /* -------------------------- OWNER FUNCTIONS -------------------------- */ /// @notice Sets the maximum number of holdings for an NFT record /// @param _maxHoldingsCount The new maximum number of holdings function setMaxHoldingsCount(uint256 _maxHoldingsCount) external onlyOwner { require(_maxHoldingsCount != 0, "NRC: INVALID_MAX_HOLDINGS"); maxHoldingsCount = _maxHoldingsCount; emit MaxHoldingsChanges(maxHoldingsCount); } /* ------------------------- FACTORY FUNCTIONS ------------------------- */ /// @notice Update the amount for a specific holding and delete /// the holding if the amount is zero. /// @param _nftId The id of the NFT /// @param _token The token/holding address /// @param _amount Updated amount for this asset function updateHoldingAmount( uint256 _nftId, address _token, uint256 _amount ) public onlyFactory { if (_amount == 0) { uint256 tokenIndex = 0; address[] memory tokens = getAssetTokens(_nftId); while (tokenIndex < tokens.length) { if (tokens[tokenIndex] == _token) { deleteAsset(_nftId, tokenIndex); break; } tokenIndex++; } } else { records[_nftId].holdings[_token] = _amount; } } /// @notice Fully delete a holding record for an NFT /// @param _nftId The id of the NFT /// @param _tokenIndex The token index in holdings array function deleteAsset(uint256 _nftId, uint256 _tokenIndex) public onlyFactory { address[] storage tokens = records[_nftId].tokens; address token = tokens[_tokenIndex]; require(records[_nftId].holdings[token] != 0, "NRC: HOLDING_INACTIVE"); delete records[_nftId].holdings[token]; tokens[_tokenIndex] = tokens[tokens.length - 1]; tokens.pop(); } /// @notice Delete a holding item in holding mapping. Does not remove token in NftRecord.tokens array /// @param _nftId NFT's identifier /// @param _token Token address for holding to remove function freeHolding(uint256 _nftId, address _token) public onlyFactory { delete records[_nftId].holdings[_token]; } /// @notice Helper function that creates a record or add the holding if record already exists /// @param _nftId The NFT's identifier /// @param _token The token/holding address /// @param _amount Amount to add for this asset /// @param _reserve Reserve address function store( uint256 _nftId, address _token, uint256 _amount, address _reserve ) external onlyFactory { NftRecord storage _nftRecord = records[_nftId]; uint256 amount = records[_nftId].holdings[_token]; require(_amount != 0, "NRC: INVALID_AMOUNT"); if (amount != 0) { require(_nftRecord.reserve == _reserve, "NRC: RESERVE_MISMATCH"); updateHoldingAmount(_nftId, _token, amount + _amount); return; } require(_nftRecord.tokens.length < maxHoldingsCount, "NRC: TOO_MANY_TOKENS"); require( _reserve != address(0) && (_reserve == _nftRecord.reserve || _nftRecord.reserve == address(0)), "NRC: INVALID_RESERVE" ); _nftRecord.holdings[_token] = _amount; _nftRecord.tokens.push(_token); _nftRecord.reserve = _reserve; } /// @notice The factory can update the lock timestamp of a NFT record /// The new timestamp must be greater than the records lockTimestamp // if block.timestamp > actual lock timestamp /// @param _nftId The NFT id to get the record /// @param _timestamp The new timestamp function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external onlyFactory { require(_timestamp > records[_nftId].lockTimestamp, "NRC: LOCK_PERIOD_CANT_DECREASE"); records[_nftId].lockTimestamp = _timestamp; emit LockTimestampIncreased(_nftId, _timestamp); } /// @notice Delete from mapping assetTokens /// @param _nftId The id of the NFT function removeNFT(uint256 _nftId) external onlyFactory { delete records[_nftId]; } /// @notice Set the reserve where assets are stored /// @param _nftId The NFT ID to update /// @param _nextReserve Address for the new reserve function setReserve(uint256 _nftId, address _nextReserve) external onlyFactory { records[_nftId].reserve = _nextReserve; emit ReserveUpdated(_nftId, _nextReserve); } /* ------------------------------- VIEWS ------------------------------- */ /// @notice Get content of assetTokens mapping /// @param _nftId The id of the NFT /// @return Array of token addresses function getAssetTokens(uint256 _nftId) public view returns (address[] memory) { return records[_nftId].tokens; } /// @notice Get reserve the assets are stored in /// @param _nftId The NFT ID /// @return The reserve address these assets are stored in function getAssetReserve(uint256 _nftId) external view returns (address) { return records[_nftId].reserve; } /// @notice Get how many tokens are in a portfolio/NFT /// @param _nftId NFT ID to examine /// @return The array length function getAssetTokensLength(uint256 _nftId) external view returns (uint256) { return records[_nftId].tokens.length; } /// @notice Get holding amount for a given nft id /// @param _nftId The id of the NFT /// @param _token The address of the token /// @return The holding amount function getAssetHolding(uint256 _nftId, address _token) public view returns (uint256) { return records[_nftId].holdings[_token]; } /// @notice Returns the holdings associated to a NestedAsset /// @param _nftId the id of the NestedAsset /// @return Two arrays with the same length : /// - The token addresses in the portfolio /// - The respective amounts function tokenHoldings(uint256 _nftId) external view returns (address[] memory, uint256[] memory) { address[] memory tokens = getAssetTokens(_nftId); uint256 tokensCount = tokens.length; uint256[] memory amounts = new uint256[](tokensCount); for (uint256 i = 0; i < tokensCount; i++) { amounts[i] = getAssetHolding(_nftId, tokens[i]); } return (tokens, amounts); } /// @notice Get the lock timestamp of a portfolio/NFT /// @param _nftId The NFT ID /// @return The lock timestamp from the NftRecord function getLockTimestamp(uint256 _nftId) external view returns (uint256) { return records[_nftId].lockTimestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "./interfaces/external/IWETH.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /// @title Native token withdrawer /// @dev Withdraw native token from the wrapper contract on behalf /// of the sender. Upgradeable proxy contracts are not able to receive /// native tokens from contracts via `transfer` (EIP1884), they need a /// middleman forwarding all available gas and reverting on errors. contract Withdrawer is ReentrancyGuard { IWETH public immutable weth; constructor(IWETH _weth) { weth = _weth; } receive() external payable { require(msg.sender == address(weth), "WD: ETH_SENDER_NOT_WETH"); } /// @notice Withdraw native token from wrapper contract /// @param amount The amount to withdraw function withdraw(uint256 amount) external nonReentrant { weth.transferFrom(msg.sender, address(this), amount); weth.withdraw(amount); Address.sendValue(payable(msg.sender), amount); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "./interfaces/IOperatorResolver.sol"; import "./abstracts/MixinOperatorResolver.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Operator Resolver implementation /// @notice Resolve the operators address contract OperatorResolver is IOperatorResolver, Ownable { /// @dev Operators map of the name and address mapping(bytes32 => Operator) public operators; /// @inheritdoc IOperatorResolver function getOperator(bytes32 name) external view override returns (Operator memory) { return operators[name]; } /// @inheritdoc IOperatorResolver function requireAndGetOperator(bytes32 name, string calldata reason) external view override returns (Operator memory) { Operator memory _foundOperator = operators[name]; require(_foundOperator.implementation != address(0), reason); return _foundOperator; } /// @inheritdoc IOperatorResolver function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations) external view override returns (bool) { uint256 namesLength = names.length; require(namesLength == destinations.length, "OR: INPUTS_LENGTH_MUST_MATCH"); for (uint256 i = 0; i < namesLength; i++) { if ( operators[names[i]].implementation != destinations[i].implementation || operators[names[i]].selector != destinations[i].selector ) { return false; } } return true; } /// @inheritdoc IOperatorResolver function importOperators( bytes32[] calldata names, Operator[] calldata operatorsToImport, MixinOperatorResolver[] calldata destinations ) external override onlyOwner { require(names.length == operatorsToImport.length, "OR: INPUTS_LENGTH_MUST_MATCH"); bytes32 name; Operator calldata destination; for (uint256 i = 0; i < names.length; i++) { name = names[i]; destination = operatorsToImport[i]; operators[name] = destination; emit OperatorImported(name, destination); } // rebuild caches atomically // see. https://github.com/code-423n4/2021-11-nested-findings/issues/217 rebuildCaches(destinations); } /// @notice rebuild the caches of mixin smart contracts /// @param destinations The list of mixinOperatorResolver to rebuild function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner { for (uint256 i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "../abstracts/MixinOperatorResolver.sol"; /// @title Operator address resolver interface interface IOperatorResolver { /// @dev Represents an operator definition /// @param implementation Contract address /// @param selector Function selector struct Operator { address implementation; bytes4 selector; } /// @notice Emitted when an operator is imported /// @param name The operator name /// @param destination The operator definition event OperatorImported(bytes32 name, Operator destination); /// @notice Get an operator (address/selector) for a given name /// @param name The operator name /// @return The operator struct (address/selector) function getOperator(bytes32 name) external view returns (Operator memory); /// @notice Get an operator (address/selector) for a given name but require the operator to exist. /// @param name The operator name /// @param reason Require message /// @return The operator struct (address/selector) function requireAndGetOperator(bytes32 name, string calldata reason) external view returns (Operator memory); /// @notice Check if some operators are imported with the right name (and vice versa) /// @dev The check is performed on the index, make sure that the two arrays match /// @param names The operator names /// @param destinations The operator addresses /// @return True if all the addresses/names are correctly imported, false otherwise function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations) external view returns (bool); /// @notice Import/replace operators /// @dev names and destinations arrays must coincide /// @param names Hashes of the operators names to register /// @param operatorsToImport Operators to import /// @param destinations Destinations to rebuild cache atomically function importOperators( bytes32[] calldata names, Operator[] calldata operatorsToImport, MixinOperatorResolver[] calldata destinations ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Asbtract "Ownable" contract managing a whitelist of factories abstract contract OwnableFactoryHandler is Ownable { /// @dev Emitted when a new factory is added /// @param newFactory Address of the new factory event FactoryAdded(address newFactory); /// @dev Emitted when a factory is removed /// @param oldFactory Address of the removed factory event FactoryRemoved(address oldFactory); /// @dev Supported factories to interact with mapping(address => bool) public supportedFactories; /// @dev Reverts the transaction if the caller is a supported factory modifier onlyFactory() { require(supportedFactories[msg.sender], "OFH: FORBIDDEN"); _; } /// @notice Add a supported factory /// @param _factory The address of the new factory function addFactory(address _factory) external onlyOwner { require(_factory != address(0), "OFH: INVALID_ADDRESS"); supportedFactories[_factory] = true; emit FactoryAdded(_factory); } /// @notice Remove a supported factory /// @param _factory The address of the factory to remove function removeFactory(address _factory) external onlyOwner { require(supportedFactories[_factory], "OFH: NOT_SUPPORTED"); supportedFactories[_factory] = false; emit FactoryRemoved(_factory); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@dev Increase the shares of a shareholder @param _account The shareholder address @param _shares The shares of the holder @param _token The updated token
function _addShares( address _account, uint256 _shares, address _token ) private { TokenRecords storage _tokenRecords = tokenRecords[_token]; _tokenRecords.shares[_account] += _shares; _tokenRecords.totalShares += _shares; }
427,683
[ 1, 382, 11908, 326, 24123, 434, 279, 7433, 4505, 225, 389, 4631, 1021, 7433, 4505, 1758, 225, 389, 30720, 1021, 24123, 434, 326, 10438, 225, 389, 2316, 1021, 3526, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 389, 1289, 24051, 12, 203, 3639, 1758, 389, 4631, 16, 203, 3639, 2254, 5034, 389, 30720, 16, 203, 3639, 1758, 389, 2316, 203, 565, 262, 3238, 288, 203, 3639, 3155, 6499, 2502, 389, 2316, 6499, 273, 1147, 6499, 63, 67, 2316, 15533, 203, 3639, 389, 2316, 6499, 18, 30720, 63, 67, 4631, 65, 1011, 389, 30720, 31, 203, 3639, 389, 2316, 6499, 18, 4963, 24051, 1011, 389, 30720, 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 ]
./full_match/1/0x97443EA7604318e38f807bf382f0E4C8C7fA71d0/sources/arb.sol
access control arb here
function uniswapV2Call(address, uint, uint _amount1, bytes calldata _data) external { require(msg.sender == WETHBTCPairAddress, "!"); uint borrowAmount = _amount1; uint fee = ((borrowAmount * 3) / 997) + 1; (uint _loop) = abi.decode(_data, (uint)); bool success1 = true; bool success2 = true; for(uint i=0; i<_loop; i++){ if(success1) (success1, ) = address(this).call(abi.encodeWithSelector(this.arb_DAI.selector)); if(success2) (success2, ) = address(this).call(abi.encodeWithSelector(this.arb_TRIBE.selector)); } IERC20(WETH).transfer(WETHBTCPairAddress, borrowAmount + fee); IWETH(WETH).withdraw(IERC20(WETH).balanceOf(address(this))); payable(owner).transfer(address(this).balance); }
4,867,518
[ 1, 3860, 3325, 419, 70, 2674, 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, 445, 640, 291, 91, 438, 58, 22, 1477, 12, 2867, 16, 2254, 16, 2254, 389, 8949, 21, 16, 1731, 745, 892, 389, 892, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 678, 1584, 44, 38, 15988, 4154, 1887, 16, 23717, 1769, 203, 3639, 2254, 29759, 6275, 273, 389, 8949, 21, 31, 203, 540, 203, 3639, 2254, 14036, 273, 14015, 70, 15318, 6275, 380, 890, 13, 342, 2468, 10580, 13, 397, 404, 31, 203, 540, 203, 3639, 261, 11890, 389, 6498, 13, 273, 24126, 18, 3922, 24899, 892, 16, 261, 11890, 10019, 203, 540, 203, 3639, 1426, 2216, 21, 273, 638, 31, 203, 3639, 1426, 2216, 22, 273, 638, 31, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 277, 32, 67, 6498, 31, 277, 27245, 95, 203, 5411, 309, 12, 4768, 21, 13, 261, 4768, 21, 16, 262, 273, 1758, 12, 2211, 2934, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 2211, 18, 6779, 67, 9793, 45, 18, 9663, 10019, 203, 5411, 309, 12, 4768, 22, 13, 261, 4768, 22, 16, 262, 273, 1758, 12, 2211, 2934, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 2211, 18, 6779, 67, 6566, 5948, 18, 9663, 10019, 203, 3639, 289, 203, 540, 203, 3639, 467, 654, 39, 3462, 12, 59, 1584, 44, 2934, 13866, 12, 59, 1584, 44, 38, 15988, 4154, 1887, 16, 29759, 6275, 397, 14036, 1769, 203, 3639, 467, 59, 1584, 44, 12, 59, 1584, 44, 2934, 1918, 9446, 12, 45, 654, 39, 3462, 12, 59, 1584, 44, 2934, 12296, 951, 2 ]
//Address: 0x856912680349a406f72e26aa994100b8ad409f87 //Contract name: EtherSport //Balance: 0 Ether //Verification Date: 11/12/2017 //Transacion Count: 1097 // CODE STARTS HERE pragma solidity ^0.4.15; contract Token { /* Total amount of tokens */ uint256 public totalSupply; /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ /// @notice send `value` token to `to` from `msg.sender` /// @param to The address of the recipient /// @param value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address to, uint value) public returns (bool); /// @notice send `value` token to `to` from `from` on the condition it is approved by `from` /// @param from The address of the sender /// @param to The address of the recipient /// @param value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address from, address to, uint value) public returns (bool); /// @notice `msg.sender` approves `spender` to spend `value` tokens /// @param spender The address of the account able to transfer the tokens /// @param value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address spender, uint value) public returns (bool); /// @param owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address owner) public constant returns (uint); /// @param owner The address of the account owning tokens /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address owner, address spender) public constant returns (uint); } contract StandardToken is Token { /* * Storage */ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; /* * Public functions */ function transfer(address to, uint value) public returns (bool) { // Do not allow transfer to 0x0 or the token contract itself require((to != 0x0) && (to != address(this))); if (balances[msg.sender] < value) revert(); // Balance too low balances[msg.sender] -= value; balances[to] += value; Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { // Do not allow transfer to 0x0 or the token contract itself require((to != 0x0) && (to != address(this))); if (balances[from] < value || allowances[from][msg.sender] < value) revert(); // Balance or allowance too low balances[to] += value; balances[from] -= value; allowances[from][msg.sender] -= value; Transfer(from, to, value); return true; } function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint) { return allowances[owner][spender]; } function balanceOf(address owner) public constant returns (uint) { return balances[owner]; } } library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract EtherSport is StandardToken { using SafeMath for uint256; /* * Metadata */ string public constant name = "Ether Sport"; string public constant symbol = "ESC"; uint8 public constant decimals = 18; uint256 public constant tokenUnit = 10 ** uint256(decimals); /* * Contract owner (Ethersport) */ address public owner; /* * Hardware wallets */ address public ethFundAddress; // Address for ETH owned by Ethersport address public escFundAddress; // Address for ESC allocated to Ethersport /* * List of token purchases per address * Same as balances[], except used for individual cap calculations, * because users can transfer tokens out during sale and reset token count in balances. */ mapping (address => uint256) public purchases; mapping (uint => address) public allocationsIndex; mapping (address => uint256) public allocations; uint public allocationsLength; mapping (string => mapping (string => uint256)) cd; //crowdsaleData; /* * Crowdsale parameters */ bool public isFinalized; bool public isStopped; uint256 public startBlock; // Block number when sale period begins uint256 public endBlock; // Block number when sale period ends uint256 public assignedSupply; // Total ESC tokens currently assigned uint256 public constant minimumPayment = 5 * (10**14); // 0.0005 ETH uint256 public constant escFund = 40 * (10**6) * tokenUnit; // 40M ESC reserved for development and user growth fund /* * Events */ event ClaimESC(address indexed _to, uint256 _value); modifier onlyBy(address _account){ require(msg.sender == _account); _; } function changeOwner(address _newOwner) onlyBy(owner) external { owner = _newOwner; } modifier respectTimeFrame() { require(block.number >= startBlock); require(block.number < endBlock); _; } modifier salePeriodCompleted() { require(block.number >= endBlock || assignedSupply.add(escFund).add(minimumPayment) > totalSupply); _; } modifier isValidState() { require(!isFinalized && !isStopped); _; } function allocate(address _escAddress, uint token) internal { allocationsIndex[allocationsLength] = _escAddress; allocations[_escAddress] = token; allocationsLength = allocationsLength + 1; } /* * Constructor */ function EtherSport( address _ethFundAddress, uint256 _startBlock, uint256 _preIcoHeight, uint256 _stage1Height, uint256 _stage2Height, uint256 _stage3Height, uint256 _stage4Height, uint256 _endBlockHeight ) public { require(_ethFundAddress != 0x0); require(_startBlock > block.number); owner = msg.sender; // Creator of contract is owner isFinalized = false; // Controls pre-sale state through crowdsale state isStopped = false; // Circuit breaker (only to be used by contract owner in case of emergency) ethFundAddress = _ethFundAddress; totalSupply = 100 * (10**6) * tokenUnit; // 100M total ESC tokens assignedSupply = 0; // Set starting assigned supply to 0 // Stages |Duration| Start date | End date | Amount of | Price per | Amount of tokens | Minimum | // | | | | tokens for sale | token in ETH | per 1 ETH | payment ETH | // --------|--------|----------------------|----------------------|-----------------|--------------|------------------|-------------| // Pre ICO | 1 week | 13.11.2017 12:00 UTC | 19.11.2017 12:00 UTC | 10,000,000 | 0.00050 | 2000.00 | 0.0005 | // 1 stage | 1 hour | 21.11.2017 12:00 UTC | 21.11.2017 13:00 UTC | 10,000,000 | 0.00100 | 1000.00 | 0.0005 | // 2 stage | 1 day | 22.11.2017 13:00 UTC | 29.11.2017 13:00 UTC | 15,000,000 | 0.00130 | 769.23 | 0.0005 | // 3 stage | 1 week | 22.11.2017 13:00 UTC | 29.11.2017 13:00 UTC | 15,000,000 | 0.00170 | 588.24 | 0.0005 | // 4 stage | 3 weeks| 29.11.2017 13:00 UTC | 20.12.2017 13:00 UTC | 20,000,000 | 0.00200 | 500.00 | 0.0005 | // --------|--------|----------------------|----------------------|-----------------|--------------|------------------|-------------| // | 70,000,000 | cd['preIco']['startBlock'] = _startBlock; cd['preIco']['endBlock'] = _startBlock + _preIcoHeight; cd['preIco']['cap'] = 10 * 10**6 * 10**18; cd['preIco']['exRate'] = 200000; cd['stage1']['startBlock'] = _startBlock + _stage1Height; cd['stage1']['endBlock'] = _startBlock + _stage2Height - 1; cd['stage1']['cap'] = 10 * 10**6 * 10**18; cd['stage1']['exRate'] = 100000; cd['stage2']['startBlock'] = _startBlock + _stage2Height; cd['stage2']['endBlock'] = _startBlock + _stage3Height - 1; cd['stage2']['cap'] = 15 * 10**6 * 10**18; cd['stage2']['exRate'] = 76923; cd['stage3']['startBlock'] = _startBlock + _stage3Height; cd['stage3']['endBlock'] = _startBlock + _stage4Height - 1; cd['stage3']['cap'] = 15 * 10**6 * 10**18; cd['stage3']['exRate'] = 58824; cd['stage4']['startBlock'] = _startBlock + _stage4Height; cd['stage4']['endBlock'] = _startBlock + _endBlockHeight; cd['stage4']['cap'] = 20 * 10**6 * 10**18; cd['stage4']['exRate'] = 50000; startBlock = _startBlock; endBlock = _startBlock +_endBlockHeight; escFundAddress = 0xfA29D004fD4139B04bda5fa2633bd7324d6f6c76; allocationsLength = 0; //• 13% (13’000’000 ESC) will remain at EtherSport for supporting the game process; allocate(escFundAddress, 0); // will remain at EtherSport for supporting the game process (remaining unassigned supply); allocate(0x610a20536e7b7A361D6c919529DBc1E037E1BEcB, 5 * 10**6 * 10**18); // will remain at EtherSport for supporting the game process; allocate(0x198bd6be0D747111BEBd5bD053a594FD63F3e87d, 4 * 10**6 * 10**18); // will remain at EtherSport for supporting the game process; allocate(0x02401E5B98202a579F0067781d66FBd4F2700Cb6, 4 * 10**6 * 10**18); // will remain at EtherSport for supporting the game process; //• 5% (5’000’000 ESC) will be allocated for the bounty campaign; allocate(0x778ACEcf52520266675b09b8F5272098D8679f43, 3 * 10**6 * 10**18); // will be allocated for the bounty campaign; allocate(0xdE96fdaFf4f865A1E27085426956748c5D4b8e24, 2 * 10**6 * 10**18); // will be allocated for the bounty campaign; //• 5% (5’000’000 ESC) will be paid to the project founders and the team; allocate(0x4E10125fc934FCADB7a30b97F9b4b642d4804e3d, 2 * 10**6 * 10**18); // will be paid to the project founders and the team; allocate(0xF391B5b62Fd43401751c65aF5D1D02D850Ab6b7c, 2 * 10**6 * 10**18); // will be paid to the project founders and the team; allocate(0x08474BcC5F8BB9EEe6cAc7CBA9b6fb1d20eF5AA4, 1 * 10**6 * 10**18); // will be paid to the project founders and the team; //• 5% (5’000’000 ESC) will be paid to the Angel investors; allocate(0x9F5818196E45ceC2d57DFc0fc0e3D7388e5de48d, 2 * 10**6 * 10**18); // will be paid to the Angel investors. allocate(0x9e43667D1e3Fb460f1f2432D0FF3203364a3d284, 2 * 10**6 * 10**18); // will be paid to the Angel investors. allocate(0x809040D6226FE73f245a0a16Dd685b5641540B74, 500 * 10**3 * 10**18); // will be paid to the Angel investors. allocate(0xaE2542d16cc3D6d487fe87Fc0C03ad0D41e46AFf, 500 * 10**3 * 10**18); // will be paid to the Angel investors. //• 1% (1’000’000 ESC) will be left in the system for building the first jackpot; allocate(0xbC82DE22610c51ACe45d3BCf03b9b3cd179731b2, 1 * 10**6 * 10**18); // will be left in the system for building the first jackpot; //• 1% (1’000’000 ESC) will be distributed among advisors; allocate(0x302Cd6D41866ec03edF421a0CD4f4cbDFB0B67b0, 800 * 10**3 * 10**18); // will be distributed among advisors; allocate(0xe190CCb2f92A0dCAc30bb4a4a92863879e5ff751, 50 * 10**3 * 10**18); // will be distributed among advisors; allocate(0xfC7cf20f29f5690dF508Dd0FB99bFCB4a7d23073, 100 * 10**3 * 10**18); // will be distributed among advisors; allocate(0x1DC97D37eCbf7D255BF4d461075936df2BdFd742, 50 * 10**3 * 10**18); // will be distributed among advisors; } /// @notice Stop sale in case of emergency (i.e. circuit breaker) /// @dev Only allowed to be called by the owner function stopSale() onlyBy(owner) external { isStopped = true; } /// @notice Restart sale in case of an emergency stop /// @dev Only allowed to be called by the owner function restartSale() onlyBy(owner) external { isStopped = false; } /// @dev Fallback function can be used to buy tokens function () payable public { claimTokens(); } /// @notice Calculate rate based on block number function calculateTokenExchangeRate() internal returns (uint256) { if (cd['preIco']['startBlock'] <= block.number && block.number <= cd['preIco']['endBlock']) { return cd['preIco']['exRate']; } if (cd['stage1']['startBlock'] <= block.number && block.number <= cd['stage1']['endBlock']) { return cd['stage1']['exRate']; } if (cd['stage2']['startBlock'] <= block.number && block.number <= cd['stage2']['endBlock']) { return cd['stage2']['exRate']; } if (cd['stage3']['startBlock'] <= block.number && block.number <= cd['stage3']['endBlock']) { return cd['stage3']['exRate']; } if (cd['stage4']['startBlock'] <= block.number && block.number <= cd['stage4']['endBlock']) { return cd['stage4']['exRate']; } // in case between Pre-ICO and ICO return 0; } function maximumTokensToBuy() constant internal returns (uint256) { uint256 maximum = 0; if (cd['preIco']['startBlock'] <= block.number) { maximum = maximum.add(cd['preIco']['cap']); } if (cd['stage1']['startBlock'] <= block.number) { maximum = maximum.add(cd['stage1']['cap']); } if (cd['stage2']['startBlock'] <= block.number) { maximum = maximum.add(cd['stage2']['cap']); } if (cd['stage3']['startBlock'] <= block.number) { maximum = maximum.add(cd['stage3']['cap']); } if (cd['stage4']['startBlock'] <= block.number) { maximum = maximum.add(cd['stage4']['cap']); } return maximum.sub(assignedSupply); } /// @notice Create `msg.value` ETH worth of ESC /// @dev Only allowed to be called within the timeframe of the sale period function claimTokens() respectTimeFrame isValidState payable public { require(msg.value >= minimumPayment); uint256 tokenExchangeRate = calculateTokenExchangeRate(); // tokenExchangeRate == 0 mean that now not valid time to take part in crowdsale event require(tokenExchangeRate > 0); uint256 tokens = msg.value.mul(tokenExchangeRate).div(100); // Check that we can sell this amount of tokens in the moment require(tokens <= maximumTokensToBuy()); // Check that we're not over totals uint256 checkedSupply = assignedSupply.add(tokens); // Return money if we're over total token supply require(checkedSupply.add(escFund) <= totalSupply); balances[msg.sender] = balances[msg.sender].add(tokens); purchases[msg.sender] = purchases[msg.sender].add(tokens); assignedSupply = checkedSupply; ClaimESC(msg.sender, tokens); // Logs token creation for UI purposes // As per ERC20 spec, a token contract which creates new tokens SHOULD trigger a Transfer event with the _from address // set to 0x0 when tokens are created (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) Transfer(0x0, msg.sender, tokens); } /// @notice Sends the ETH to ETH fund wallet and finalizes the token sale function finalize() salePeriodCompleted isValidState onlyBy(owner) external { // Upon successful completion of sale, send tokens to ESC fund balances[escFundAddress] = balances[escFundAddress].add(escFund); assignedSupply = assignedSupply.add(escFund); ClaimESC(escFundAddress, escFund); // Log tokens claimed by Ethersport ESC fund Transfer(0x0, escFundAddress, escFund); for(uint i=0;i<allocationsLength;i++) { balances[allocationsIndex[i]] = balances[allocationsIndex[i]].add(allocations[allocationsIndex[i]]); ClaimESC(allocationsIndex[i], allocations[allocationsIndex[i]]); // Log tokens claimed by Ethersport ESC fund Transfer(0x0, allocationsIndex[i], allocations[allocationsIndex[i]]); } // In the case where not all 70M ESC allocated to crowdfund participants // is sold, send the remaining unassigned supply to ESC fund address, // which will then be used to fund the user growth pool. if (assignedSupply < totalSupply) { uint256 unassignedSupply = totalSupply.sub(assignedSupply); balances[escFundAddress] = balances[escFundAddress].add(unassignedSupply); assignedSupply = assignedSupply.add(unassignedSupply); ClaimESC(escFundAddress, unassignedSupply); // Log tokens claimed by Ethersport ESC fund Transfer(0x0, escFundAddress, unassignedSupply); } ethFundAddress.transfer(this.balance); isFinalized = true; // Finalize sale } }
will remain at EtherSport for supporting the game process;
allocate(0x610a20536e7b7A361D6c919529DBc1E037E1BEcB, 5 * 10**6 * 10**18);
2,488,269
[ 1, 20194, 7232, 622, 512, 1136, 55, 655, 364, 22930, 326, 7920, 1207, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 10101, 12, 20, 92, 26, 2163, 69, 31777, 5718, 73, 27, 70, 27, 37, 5718, 21, 40, 26, 71, 29, 31677, 5540, 2290, 71, 21, 41, 4630, 27, 41, 21, 5948, 71, 38, 16, 1381, 380, 1728, 636, 26, 380, 1728, 636, 2643, 1769, 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 ]
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_53(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,766
[ 1, 6241, 30, 1410, 10929, 3560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6617, 537, 67, 8643, 12, 2867, 17571, 264, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 1529, 13, 288, 203, 565, 389, 12908, 4524, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 3626, 1716, 685, 1125, 12, 1234, 18, 15330, 16, 17571, 264, 16, 460, 11272, 203, 565, 327, 638, 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 ]
./partial_match/1/0x08940c2C47100587412bCF94DD0e784D1E8dF3AA/sources/RevShareContract.sol
send specified amount to the incentives address immediately
payable(incentivesAddress).transfer(incentivesRevenue);
15,535,727
[ 1, 4661, 1269, 3844, 358, 326, 316, 2998, 3606, 1758, 7636, 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, 8843, 429, 12, 267, 2998, 3606, 1887, 2934, 13866, 12, 267, 2998, 3606, 426, 24612, 1769, 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 ]
pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable // @dev Interface of the asset proxy's assetData. // The asset proxies take an ABI encoded `bytes assetData` as argument. // This argument is ABI encoded as one of the methods of this interface. interface IAssetData { /// @dev Function signature for encoding ERC20 assetData. /// @param tokenAddress Address of ERC20Token contract. function ERC20Token(address tokenAddress) external; /// @dev Function signature for encoding ERC721 assetData. /// @param tokenAddress Address of ERC721 token contract. /// @param tokenId Id of ERC721 token to be transferred. function ERC721Token( address tokenAddress, uint256 tokenId ) external; /// @dev Function signature for encoding ERC1155 assetData. /// @param tokenAddress Address of ERC1155 token contract. /// @param tokenIds Array of ids of tokens to be transferred. /// @param values Array of values that correspond to each token id to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function. function ERC1155Assets( address tokenAddress, uint256[] calldata tokenIds, uint256[] calldata values, bytes calldata callbackData ) external; /// @dev Function signature for encoding MultiAsset assetData. /// @param values Array of amounts that correspond to each asset to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract. function MultiAsset( uint256[] calldata values, bytes[] calldata nestedAssetData ) external; /// @dev Function signature for encoding StaticCall assetData. /// @param staticCallTargetAddress Address that will execute the staticcall. /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress. /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data. function StaticCall( address staticCallTargetAddress, bytes calldata staticCallData, bytes32 expectedReturnDataHash ) external; /// @dev Function signature for encoding ERC20Bridge assetData. /// @param tokenAddress Address of token to transfer. /// @param bridgeAddress Address of the bridge contract. /// @param bridgeData Arbitrary data to be passed to the bridge contract. function ERC20Bridge( address tokenAddress, address bridgeAddress, bytes calldata bridgeData ) external; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } library LibOrder { using LibOrder for Order; // Hash for the EIP712 Order Schema: // keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData,", // "bytes makerFeeAssetData,", // "bytes takerFeeAssetData", // ")" // )) bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH = 0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534; // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's status is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } // solhint-enable max-line-length /// @dev Order information returned by `getOrderInfo()`. struct OrderInfo { OrderStatus orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates the EIP712 typed data hash of an order with a given domain separator. /// @param order The order structure. /// @return EIP712 typed data hash of the order. function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 orderHash) { orderHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, order.getStructHash() ); return orderHash; } /// @dev Calculates EIP712 hash of the order struct. /// @param order The order structure. /// @return EIP712 hash of the order struct. function getStructHash(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH; bytes memory makerAssetData = order.makerAssetData; bytes memory takerAssetData = order.takerAssetData; bytes memory makerFeeAssetData = order.makerFeeAssetData; bytes memory takerFeeAssetData = order.takerFeeAssetData; // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // uint256(order.makerAddress), // uint256(order.takerAddress), // uint256(order.feeRecipientAddress), // uint256(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData), // keccak256(order.makerFeeAssetData), // keccak256(order.takerFeeAssetData) // )); assembly { // Assert order offset (this is an internal error that should never be triggered) if lt(order, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) let pos4 := add(order, 384) let pos5 := add(order, 416) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) let temp4 := mload(pos4) let temp5 := mload(pos5) // Hash in place mstore(pos1, schemaHash) mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData result := keccak256(pos1, 480) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) mstore(pos4, temp4) mstore(pos5, temp5) } return result; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } library LibMathRichErrors { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } library LibMath { using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev 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 True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `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 Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title ERC-1155 Multi Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md /// Note: The ERC-165 identifier for this interface is 0xd9b67a26. interface IERC1155 { /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. ///Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /// @dev MUST emit when an approval is updated. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /// @dev MUST emit when the URI is updated for a token ID. /// URIs are defined in RFC 3986. /// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". event URI( string value, uint256 indexed id ); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. /// @param operator Address to add to the set of authorized operators /// @param approved True if the operator is approved, false to revoke approval function setApprovalForAll(address operator, bool approved) external; /// @notice Queries the approval status of an operator for a given owner. /// @param owner The owner of the Tokens /// @param operator Address of authorized operator /// @return True if the operator is approved, false if not function isApprovedForAll(address owner, address operator) external view returns (bool); /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external view returns (uint256); /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return The _owner's balance of the Token types requested function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibAssetDataTransferRichErrors { // bytes4(keccak256("UnsupportedAssetProxyError(bytes4)")) bytes4 internal constant UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR = 0x7996a271; // bytes4(keccak256("Erc721AmountMustEqualOneError(uint256)")) bytes4 internal constant ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR = 0xbaffa474; // solhint-disable func-name-mixedcase function UnsupportedAssetProxyError( bytes4 proxyId ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR, proxyId ); } function Erc721AmountMustEqualOneError( uint256 amount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR, amount ); } } library LibAssetDataTransfer { using LibBytes for bytes; using LibSafeMath for uint256; using LibAssetDataTransfer for bytes; /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal { if (amount == 0) { return; } bytes4 proxyId = assetData.readBytes4(0); if ( proxyId == IAssetData(address(0)).ERC20Token.selector || proxyId == IAssetData(address(0)).ERC20Bridge.selector ) { assetData.transferERC20Token( from, to, amount ); } else if (proxyId == IAssetData(address(0)).ERC721Token.selector) { assetData.transferERC721Token( from, to, amount ); } else if (proxyId == IAssetData(address(0)).ERC1155Assets.selector) { assetData.transferERC1155Assets( from, to, amount ); } else if (proxyId == IAssetData(address(0)).MultiAsset.selector) { assetData.transferMultiAsset( from, to, amount ); } else if (proxyId != IAssetData(address(0)).StaticCall.selector) { LibRichErrors.rrevert(LibAssetDataTransferRichErrors.UnsupportedAssetProxyError( proxyId )); } } ///@dev Transfer asset from sender to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferIn( bytes memory assetData, uint256 amount ) internal { assetData.transferFrom( msg.sender, address(this), amount ); } ///@dev Transfer asset from this contract to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferOut( bytes memory assetData, uint256 amount ) internal { assetData.transferFrom( address(this), msg.sender, amount ); } /// @dev Decodes ERC20 or ERC20Bridge assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, address from, address to, uint256 amount ) internal { address token = assetData.readAddress(16); // Transfer tokens. if (from == address(this)) { LibERC20Token.transfer( token, to, amount ); } else { LibERC20Token.transferFrom( token, from, to, amount ); } } /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, address from, address to, uint256 amount ) internal { if (amount != 1) { LibRichErrors.rrevert(LibAssetDataTransferRichErrors.Erc721AmountMustEqualOneError( amount )); } // Decode asset data. address token = assetData.readAddress(16); uint256 tokenId = assetData.readUint256(36); // Perform transfer. IERC721Token(token).transferFrom( from, to, tokenId ); } /// @dev Decodes ERC1155 assetData and transfers given amounts to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC1155Assets( bytes memory assetData, address from, address to, uint256 amount ) internal { // Decode assetData // solhint-disable ( address token, uint256[] memory ids, uint256[] memory values, bytes memory data ) = abi.decode( assetData.slice(4, assetData.length), (address, uint256[], uint256[], bytes) ); // solhint-enable // Scale up values by `amount` uint256 length = values.length; uint256[] memory scaledValues = new uint256[](length); for (uint256 i = 0; i != length; i++) { scaledValues[i] = values[i].safeMul(amount); } // Execute `safeBatchTransferFrom` call // Either succeeds or throws IERC1155(token).safeBatchTransferFrom( from, to, ids, scaledValues, data ); } /// @dev Decodes MultiAsset assetData and recursively transfers assets to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferMultiAsset( bytes memory assetData, address from, address to, uint256 amount ) internal { // solhint-disable indent (uint256[] memory nestedAmounts, bytes[] memory nestedAssetData) = abi.decode( assetData.slice(4, assetData.length), (uint256[], bytes[]) ); // solhint-enable indent uint256 numNestedAssets = nestedAssetData.length; for (uint256 i = 0; i != numNestedAssets; i++) { transferFrom( nestedAssetData[i], from, to, amount.safeMul(nestedAmounts[i]) ); } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations \under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibFillResults { using LibSafeMath for uint256; struct BatchMatchedFillResults { FillResults[] left; // Fill results for left orders FillResults[] right; // Fill results for right orders uint256 profitInLeftMakerAsset; // Profit taken from left makers uint256 profitInRightMakerAsset; // Profit taken from right makers } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 profitInLeftMakerAsset; // Profit taken from the left maker uint256 profitInRightMakerAsset; // Profit taken from the right maker } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; } /// @dev Calculates fill amounts for the matched orders. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the leftOrder order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftOrderTakerAssetFilledAmount Amount of left order already filled. /// @param rightOrderTakerAssetFilledAmount Amount of right order already filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use /// the maximal fill order matching strategy. /// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders. function calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftOrderTakerAssetFilledAmount, uint256 rightOrderTakerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice, bool shouldMaximallyFillOrders ) internal pure returns (MatchedFillResults memory matchedFillResults) { // Derive maker asset amounts for left & right orders, given store taker assert amounts uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount); uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, leftTakerAssetAmountRemaining ); uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount); uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, rightTakerAssetAmountRemaining ); // Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets. if (shouldMaximallyFillOrders) { matchedFillResults = _calculateMatchedFillResultsWithMaximalFill( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else { matchedFillResults = _calculateMatchedFillResults( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Compute fees for left order matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee ); matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee ); // Compute fees for right order matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee ); matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee ); // Compute the protocol fee that should be paid for a single fill. In this // case this should be made the protocol fee for both the left and right orders. uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier); matchedFillResults.left.protocolFeePaid = protocolFee; matchedFillResults.right.protocolFeePaid = protocolFee; // Return fill results return matchedFillResults; } /// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results. function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only /// awards profit denominated in the left maker asset. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate fill results for maker and taker assets: at least one order will be fully filled. // The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining` // The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining` // We have two distinct cases for calculating the fill results: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // If the left maker can buy exactly what the right maker can sell, then both orders are fully filled. // Case 2. // If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled. // Case 3. // If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) { // Case 2: Left order is fully filled matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. // We favor the maker when the exchange rate must be rounded. matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount ); } else { // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining // Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but // this calculation will be more precise since it does not include rounding. matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); return matchedFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching /// strategy. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResultsWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset. bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining; bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining; // Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled. // // The maximum that the left maker can possibly buy is the amount that the right order can sell. // The maximum that the right maker can possibly buy is the amount that the left order can sell. // // If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled, // the profit will be out in the right maker asset. // // There are three cases to consider: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // Case 2. // If the right maker can buy more than the left maker can sell, then only the right order is fully filled. // Case 3. // If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of // what the right maker can buy, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled with the profit paid in the left makerAsset matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) { // Case 2: Left order is fully filled with the profit paid in the right makerAsset. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round down to ensure the right maker's exchange rate does not exceed the price specified by the order. // We favor the right maker when the exchange rate must be rounded and the profit is being paid in the // right maker asset. matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftMakerAssetAmountRemaining ); matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining; } else { // Case 3: The right and left orders are fully filled matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit. if (doesLeftMakerAssetProfitExist) { matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); } // Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit. if (doesRightMakerAssetProfitExist) { matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub( matchedFillResults.left.takerAssetFilledAmount ); } return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; } } contract IExchangeCore { // Fill event is emitted whenever an order is filled. event Fill( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that received fees. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset. bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset. bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash). address takerAddress, // Address that filled the order. address senderAddress, // Address that called the Exchange contract (msg.sender). uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker. uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker. uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker. uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker. uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract. ); // Cancel event is emitted whenever an individual order is cancelled. event Cancel( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. address senderAddress, // Address that called the Exchange contract (msg.sender). bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash). ); // CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully. event CancelUpTo( address indexed makerAddress, // Orders cancelled must have been created by this address. address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address. uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled. ); /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external payable; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public payable; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IProtocolFees { // Logs updates to the protocol fee multiplier. event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier); // Logs updates to the protocolFeeCollector address. event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector); /// @dev Allows the owner to update the protocol fee multiplier. /// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier) external; /// @dev Allows the owner to update the protocolFeeCollector address. /// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address. function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external; /// @dev Returns the protocolFeeMultiplier function protocolFeeMultiplier() external view returns (uint256); /// @dev Returns the protocolFeeCollector address function protocolFeeCollector() external view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IMatchOrders { /// @dev Match complementary orders that have a profitable spread. /// Each order is filled at their respective price point, and /// the matcher receives a profit denominated in the left maker asset. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrders( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrdersWithMaximalFill( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled by maker and taker of matched orders. function matchOrdersWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibZeroExTransaction { using LibZeroExTransaction for ZeroExTransaction; // Hash for the EIP712 0x transaction schema // keccak256(abi.encodePacked( // "ZeroExTransaction(", // "uint256 salt,", // "uint256 expirationTimeSeconds,", // "uint256 gasPrice,", // "address signerAddress,", // "bytes data", // ")" // )); bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508; struct ZeroExTransaction { uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash. uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires. uint256 gasPrice; // gasPrice that transaction is required to be executed with. address signerAddress; // Address of transaction signer. bytes data; // AbiV2 encoded calldata. } /// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction. function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; } /// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct. function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; } } contract ISignatureValidator { // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 EIP1271Wallet, // 0x07 NSignatureTypes // 0x08, number of signature types. Always leave at end. } event SignatureValidatorApproval( address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures. address indexed validatorAddress, // Address of signature validator contract. bool isApproved // Approval or disapproval of validator contract. ); /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external payable; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external payable; /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given order and signer. function isValidOrderSignature( LibOrder.Order memory order, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given transaction and signer. function isValidTransactionSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( LibOrder.Order memory order, bytes32 orderHash, bytes memory signature ) internal view returns (bool isValid); /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes32 transactionHash, bytes memory signature ) internal view returns (bool isValid); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ITransactions { // TransactionExecution event is emitted when a ZeroExTransaction is executed. event TransactionExecution(bytes32 indexed transactionHash); /// @dev Executes an Exchange method call in the context of signer. /// @param transaction 0x transaction containing salt, signerAddress, and data. /// @param signature Proof that transaction has been signed by signer. /// @return ABI encoded return data of the underlying Exchange function call. function executeTransaction( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public payable returns (bytes memory); /// @dev Executes a batch of Exchange method calls in the context of signer(s). /// @param transactions Array of 0x transactions containing salt, signerAddress, and data. /// @param signatures Array of proofs that transactions have been signed by signer(s). /// @return Array containing ABI encoded return data for each of the underlying Exchange function calls. function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory); /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function _getCurrentContextAddress() internal view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IAssetProxyDispatcher { // Logs registration of new asset proxy event AssetProxyRegistered( bytes4 id, // Id of new registered AssetProxy. address assetProxy // Address of new registered AssetProxy. ); /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrKillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Minimum amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Minimum amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of cancelOrder. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public payable; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ITransferSimulator { /// @dev This function may be used to simulate any amount of transfers /// As they would occur through the Exchange contract. Note that this function /// will always revert, even if all transfers are successful. However, it may /// be used with eth_call or with a try/catch pattern in order to simulate /// the results of the transfers. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @param fromAddresses Array containing the `from` addresses that correspond with each transfer. /// @param toAddresses Array containing the `to` addresses that correspond with each transfer. /// @param amounts Array containing the amounts that correspond to each transfer. /// @return This function does not return a value. However, it will always revert with /// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. function simulateDispatchTransferFromCalls( bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) public; } // solhint-disable no-empty-blocks contract IExchange is IProtocolFees, IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, ITransferSimulator, IWrapperFunctions {} /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibWethUtilsRichErrors { // bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; // bytes4(keccak256("InsufficientEthForFeeError(uint256,uint256)")) bytes4 internal constant INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR = 0xecf40fd9; // bytes4(keccak256("DefaultFunctionWethContractOnlyError(address)")) bytes4 internal constant DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR = 0x08b18698; // bytes4(keccak256("EthFeeLengthMismatchError(uint256,uint256)")) bytes4 internal constant ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR = 0x3ecb6ceb; // solhint-disable func-name-mixedcase function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function InsufficientEthForFeeError( uint256 ethFeeRequired, uint256 ethAvailable ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR, ethFeeRequired, ethAvailable ); } function DefaultFunctionWethContractOnlyError( address senderAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR, senderAddress ); } function EthFeeLengthMismatchError( uint256 ethFeesLength, uint256 feeRecipientsLength ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR, ethFeesLength, feeRecipientsLength ); } } contract MixinWethUtils { uint256 constant internal MAX_UINT256 = uint256(-1); // solhint-disable var-name-mixedcase IEtherToken internal WETH; bytes internal WETH_ASSET_DATA; // solhint-enable var-name-mixedcase using LibSafeMath for uint256; constructor ( address exchange, address weth ) public { WETH = IEtherToken(weth); WETH_ASSET_DATA = abi.encodeWithSelector( IAssetData(address(0)).ERC20Token.selector, weth ); address proxyAddress = IExchange(exchange).getAssetProxy(IAssetData(address(0)).ERC20Token.selector); if (proxyAddress == address(0)) { LibRichErrors.rrevert(LibWethUtilsRichErrors.UnregisteredAssetProxyError()); } WETH.approve(proxyAddress, MAX_UINT256); address protocolFeeCollector = IExchange(exchange).protocolFeeCollector(); if (protocolFeeCollector != address(0)) { WETH.approve(protocolFeeCollector, MAX_UINT256); } } /// @dev Default payable function, this allows us to withdraw WETH function () external payable { if (msg.sender != address(WETH)) { LibRichErrors.rrevert(LibWethUtilsRichErrors.DefaultFunctionWethContractOnlyError( msg.sender )); } } /// @dev Transfers ETH denominated fees to all feeRecipient addresses /// @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to corresponding feeRecipients. /// @param feeRecipients Addresses that will receive ETH when orders are filled. /// @return ethRemaining msg.value minus the amount of ETH spent on affiliate fees. function _transferEthFeesAndWrapRemaining( uint256[] memory ethFeeAmounts, address payable[] memory feeRecipients ) internal returns (uint256 ethRemaining) { uint256 feesLen = ethFeeAmounts.length; // ethFeeAmounts len must equal feeRecipients len if (feesLen != feeRecipients.length) { LibRichErrors.rrevert(LibWethUtilsRichErrors.EthFeeLengthMismatchError( feesLen, feeRecipients.length )); } // This function is always called before any other function, so we assume that // the ETH remaining is the entire msg.value. ethRemaining = msg.value; for (uint256 i = 0; i != feesLen; i++) { uint256 ethFeeAmount = ethFeeAmounts[i]; // Ensure there is enough ETH to pay the fee if (ethRemaining < ethFeeAmount) { LibRichErrors.rrevert(LibWethUtilsRichErrors.InsufficientEthForFeeError( ethFeeAmount, ethRemaining )); } // Decrease ethRemaining and transfer fee to corresponding feeRecipient ethRemaining = ethRemaining.safeSub(ethFeeAmount); feeRecipients[i].transfer(ethFeeAmount); } // Convert remaining ETH to WETH. WETH.deposit.value(ethRemaining)(); return ethRemaining; } /// @dev Unwraps WETH and transfers ETH to msg.sender. /// @param transferAmount Amount of WETH balance to unwrap and transfer. function _unwrapAndTransferEth( uint256 transferAmount ) internal { // Do nothing if amount is zero if (transferAmount > 0) { // Convert WETH to ETH WETH.withdraw(transferAmount); // Transfer ETH to sender msg.sender.transfer(transferAmount); } } /// @dev transfers ETH to address. /// @param transferAmount Amount of eth to transfer. function _transferEthToAddress( uint256 transferAmount, address transferAddress ) internal { // Do nothing if amount is zero if (transferAmount > 0) { address payable transferAddresspayable = address(uint160(transferAddress)); transferAddresspayable.transfer(transferAmount); } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IOwnable { /// @dev Emitted by Ownable when ownership is transferred. /// @param previousOwner The previous owner of the contract. /// @param newOwner The new owner of the contract. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev Transfers ownership of the contract to a new address. /// @param newOwner The address that will become the owner. function transferOwnership(address newOwner) public; } library LibOwnableRichErrors { // bytes4(keccak256("OnlyOwnerError(address,address)")) bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = 0x1de45ad1; // bytes4(keccak256("TransferOwnerToZeroError()")) bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = hex"e69edc3e"; // solhint-disable func-name-mixedcase function OnlyOwnerError( address sender, address owner ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ONLY_OWNER_ERROR_SELECTOR, sender, owner ); } function TransferOwnerToZeroError() internal pure returns (bytes memory) { return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES; } } contract Ownable is IOwnable { /// @dev The owner of this contract. /// @return 0 The owner address. address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { _assertSenderIsOwner(); _; } /// @dev Change the owner of this contract. /// @param newOwner New owner address. function transferOwnership(address newOwner) public onlyOwner { if (newOwner == address(0)) { LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError()); } else { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } function _assertSenderIsOwner() internal view { if (msg.sender != owner) { LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError( msg.sender, owner )); } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibForwarderRichErrors { // bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; // bytes4(keccak256("CompleteBuyFailedError(uint256,uint256)")) bytes4 internal constant COMPLETE_BUY_FAILED_ERROR_SELECTOR = 0x91353a0c; // bytes4(keccak256("CompleteSellFailedError(uint256,uint256)")) bytes4 internal constant COMPLETE_SELL_FAILED_ERROR_SELECTOR = 0x450a0219; // bytes4(keccak256("UnsupportedFeeError(bytes)")) bytes4 internal constant UNSUPPORTED_FEE_ERROR_SELECTOR = 0x31360af1; // bytes4(keccak256("OverspentWethError(uint256,uint256)")) bytes4 internal constant OVERSPENT_WETH_ERROR_SELECTOR = 0xcdcbed5d; // solhint-disable func-name-mixedcase function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function CompleteBuyFailedError( uint256 expectedAssetBuyAmount, uint256 actualAssetBuyAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_BUY_FAILED_ERROR_SELECTOR, expectedAssetBuyAmount, actualAssetBuyAmount ); } function CompleteSellFailedError( uint256 expectedAssetSellAmount, uint256 actualAssetSellAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_SELL_FAILED_ERROR_SELECTOR, expectedAssetSellAmount, actualAssetSellAmount ); } function UnsupportedFeeError( bytes memory takerFeeAssetData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UNSUPPORTED_FEE_ERROR_SELECTOR, takerFeeAssetData ); } function OverspentWethError( uint256 wethSpent, uint256 msgValue ) internal pure returns (bytes memory) { return abi.encodeWithSelector( OVERSPENT_WETH_ERROR_SELECTOR, wethSpent, msgValue ); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IExchangeV2 { // solhint-disable max-line-length struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted. uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy. } // solhint-enable max-line-length struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s). } struct OrderInfo { uint8 orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (FillResults memory fillResults); /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(Order memory order) public returns (OrderInfo memory orderInfo); } contract MixinExchangeWrapper { // The v2 order id is the first 4 bytes of the ExchangeV2 order schema hash. // bytes4(keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData", // ")" // ))); bytes4 constant public EXCHANGE_V2_ORDER_ID = 0x770501f8; bytes4 constant internal ERC20_BRIDGE_PROXY_ID = 0xdc1600f3; // solhint-disable var-name-mixedcase IExchange internal EXCHANGE; IExchangeV2 internal EXCHANGE_V2; // solhint-enable var-name-mixedcase using LibBytes for bytes; using LibAssetDataTransfer for bytes; using LibSafeMath for uint256; constructor ( address _exchange, address _exchangeV2 ) public { EXCHANGE = IExchange(_exchange); EXCHANGE_V2 = IExchangeV2(_exchangeV2); } struct SellFillResults { uint256 wethSpentAmount; uint256 makerAssetAcquiredAmount; uint256 protocolFeePaid; } /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { if (_isV2Order(order)) { return _fillV2OrderNoThrow( order, takerAssetFillAmount, signature ); } return _fillV3OrderNoThrow( order, takerAssetFillAmount, signature ); } /// @dev Executes a single call of fillOrder according to the wethSellAmount and /// the amount already sold. /// @param order A single order specification. /// @param signature Signature for the given order. /// @param remainingTakerAssetFillAmount Remaining amount of WETH to sell. /// @return wethSpentAmount Amount of WETH spent on the given order. /// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order. function _marketSellSingleOrder( LibOrder.Order memory order, bytes memory signature, uint256 remainingTakerAssetFillAmount ) internal returns (SellFillResults memory sellFillResults) { // If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance. bytes4 makerAssetProxyId = order.makerAssetData.readBytes4(0); address tokenAddress; uint256 balanceBefore; if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { tokenAddress = order.makerAssetData.readAddress(16); balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this)); } // No taker fee or percentage fee if ( order.takerFee == 0 || _areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData) ) { // Attempt to sell the remaining amount of WETH LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount; sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid; // Subtract fee from makerAssetFilledAmount for the net amount acquired. sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount .safeSub(singleFillResults.takerFeePaid); // WETH fee } else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData)) { // We will first sell WETH as the takerAsset, then use it to pay the takerFee. // This ensures that we reserve enough to pay the taker and protocol fees. uint256 takerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.takerAssetAmount.safeAdd(order.takerFee), remainingTakerAssetFillAmount ); LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, takerAssetFillAmount, signature ); // WETH is also spent on the taker fee, so we add it here. sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.takerFeePaid); sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount; sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid; // Unsupported fee } else { LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData)); } // Account for the ERC20Bridge transfering more of the maker asset than expected. if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this)); sellFillResults.makerAssetAcquiredAmount = LibSafeMath.max256( balanceAfter.safeSub(balanceBefore), sellFillResults.makerAssetAcquiredAmount ); } order.makerAssetData.transferOut(sellFillResults.makerAssetAcquiredAmount); return sellFillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketSellNoThrow( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 protocolFee = tx.gasprice.safeMul(EXCHANGE.protocolFeeMultiplier()); for (uint256 i = 0; i != orders.length; i++) { // Preemptively skip to avoid division by zero in _marketSellSingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } // The remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); uint256 currentProtocolFee = _isV2Order(orders[i]) ? 0 : protocolFee; if (remainingTakerAssetFillAmount > currentProtocolFee) { // Do not count the protocol fee as part of the fill amount. remainingTakerAssetFillAmount = remainingTakerAssetFillAmount.safeSub(currentProtocolFee); } else { // Stop if we don't have at least enough ETH to pay another protocol fee. break; } SellFillResults memory sellFillResults = _marketSellSingleOrder( orders[i], signatures[i], remainingTakerAssetFillAmount ); totalWethSpentAmount = totalWethSpentAmount .safeAdd(sellFillResults.wethSpentAmount) .safeAdd(sellFillResults.protocolFeePaid); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(sellFillResults.makerAssetAcquiredAmount); // Stop execution if the entire amount of WETH has been sold if (totalWethSpentAmount >= wethSellAmount) { break; } } } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH (exclusive of protocol fee) /// has been sold by taker. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketSellExactAmountNoThrow( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 totalProtocolFeePaid; for (uint256 i = 0; i != orders.length; i++) { // Preemptively skip to avoid division by zero in _marketSellSingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } // The remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); SellFillResults memory sellFillResults = _marketSellSingleOrder( orders[i], signatures[i], remainingTakerAssetFillAmount ); totalWethSpentAmount = totalWethSpentAmount .safeAdd(sellFillResults.wethSpentAmount); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(sellFillResults.makerAssetAcquiredAmount); totalProtocolFeePaid = totalProtocolFeePaid.safeAdd(sellFillResults.protocolFeePaid); // Stop execution if the entire amount of WETH has been sold if (totalWethSpentAmount >= wethSellAmount) { break; } } totalWethSpentAmount = totalWethSpentAmount.safeAdd(totalProtocolFeePaid); } /// @dev Executes a single call of fillOrder according to the makerAssetBuyAmount and /// the amount already bought. /// @param order A single order specification. /// @param signature Signature for the given order. /// @param remainingMakerAssetFillAmount Remaining amount of maker asset to buy. /// @return wethSpentAmount Amount of WETH spent on the given order. /// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order. function _marketBuySingleOrder( LibOrder.Order memory order, bytes memory signature, uint256 remainingMakerAssetFillAmount ) internal returns ( uint256 wethSpentAmount, uint256 makerAssetAcquiredAmount ) { // No taker fee or WETH fee if ( order.takerFee == 0 || _areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData) ) { // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); // WETH is also spent on the protocol and taker fees, so we add it here. wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.takerFeePaid) .safeAdd(singleFillResults.protocolFeePaid); makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount; // Percentage fee } else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData)) { // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.makerAssetAmount.safeSub(order.takerFee), remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.protocolFeePaid); // Subtract fee from makerAssetFilledAmount for the net amount acquired. makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount .safeSub(singleFillResults.takerFeePaid); // Unsupported fee } else { LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData)); } return (wethSpentAmount, makerAssetAcquiredAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is acquired. /// Note that the Forwarder may fill more than the makerAssetBuyAmount so that, after percentage fees /// are paid, the net amount acquired after fees is equal to makerAssetBuyAmount (modulo rounding). /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetBuyAmount Desired amount of makerAsset to fill. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketBuyFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetBuyAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // Preemptively skip to avoid division by zero in _marketBuySingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } uint256 remainingMakerAssetFillAmount = makerAssetBuyAmount .safeSub(totalMakerAssetAcquiredAmount); // If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance. bytes4 makerAssetProxyId = orders[i].makerAssetData.readBytes4(0); address tokenAddress; uint256 balanceBefore; if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { tokenAddress = orders[i].makerAssetData.readAddress(16); balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this)); } ( uint256 wethSpentAmount, uint256 makerAssetAcquiredAmount ) = _marketBuySingleOrder( orders[i], signatures[i], remainingMakerAssetFillAmount ); // Account for the ERC20Bridge transfering more of the maker asset than expected. if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this)); makerAssetAcquiredAmount = LibSafeMath.max256( balanceAfter.safeSub(balanceBefore), makerAssetAcquiredAmount ); } orders[i].makerAssetData.transferOut(makerAssetAcquiredAmount); totalWethSpentAmount = totalWethSpentAmount .safeAdd(wethSpentAmount); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(makerAssetAcquiredAmount); // Stop execution if the entire amount of makerAsset has been bought if (totalMakerAssetAcquiredAmount >= makerAssetBuyAmount) { break; } } if (totalMakerAssetAcquiredAmount < makerAssetBuyAmount) { LibRichErrors.rrevert(LibForwarderRichErrors.CompleteBuyFailedError( makerAssetBuyAmount, totalMakerAssetAcquiredAmount )); } } /// @dev Fills the input ExchangeV2 order. The `makerFeeAssetData` must be // equal to EXCHANGE_V2_ORDER_ID (0x770501f8). /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillV2OrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { // Strip v3 specific fields from order IExchangeV2.Order memory v2Order = IExchangeV2.Order({ makerAddress: order.makerAddress, takerAddress: order.takerAddress, feeRecipientAddress: order.feeRecipientAddress, senderAddress: order.senderAddress, makerAssetAmount: order.makerAssetAmount, takerAssetAmount: order.takerAssetAmount, // NOTE: We assume fees are 0 for all v2 orders. Orders with non-zero fees will fail to be filled. makerFee: 0, takerFee: 0, expirationTimeSeconds: order.expirationTimeSeconds, salt: order.salt, makerAssetData: order.makerAssetData, takerAssetData: order.takerAssetData }); // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abi.encodeWithSelector( IExchangeV2(address(0)).fillOrder.selector, v2Order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE_V2); (bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata); if (didSucceed) { assert(returnData.length == 128); // NOTE: makerFeePaid, takerFeePaid, and protocolFeePaid will always be 0 for v2 orders (fillResults.makerAssetFilledAmount, fillResults.takerAssetFilledAmount) = abi.decode(returnData, (uint256, uint256)); } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Fills the input ExchangeV3 order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillV3OrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abi.encodeWithSelector( IExchange(address(0)).fillOrder.selector, order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE); (bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata); if (didSucceed) { assert(returnData.length == 160); fillResults = abi.decode(returnData, (LibFillResults.FillResults)); } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Checks whether one asset is effectively equal to another asset. /// This is the case if they have the same ERC20Proxy/ERC20BridgeProxy asset data, or if /// one is the ERC20Bridge equivalent of the other. /// @param assetData1 Byte array encoded for the takerFee asset proxy. /// @param assetData2 Byte array encoded for the maker asset proxy. /// @return areEqual Whether or not the underlying assets are equal. function _areUnderlyingAssetsEqual( bytes memory assetData1, bytes memory assetData2 ) internal pure returns (bool) { bytes4 assetProxyId1 = assetData1.readBytes4(0); bytes4 assetProxyId2 = assetData2.readBytes4(0); bytes4 erc20ProxyId = IAssetData(address(0)).ERC20Token.selector; bytes4 erc20BridgeProxyId = IAssetData(address(0)).ERC20Bridge.selector; if ( (assetProxyId1 == erc20ProxyId || assetProxyId1 == erc20BridgeProxyId) && (assetProxyId2 == erc20ProxyId || assetProxyId2 == erc20BridgeProxyId) ) { // Compare the underlying token addresses. address token1 = assetData1.readAddress(16); address token2 = assetData2.readAddress(16); return (token1 == token2); } else { return assetData1.equals(assetData2); } } /// @dev Checks whether an order is a v2 order. /// @param order Order struct containing order specifications. /// @return True if the order's `makerFeeAssetData` is set to the v2 order id. function _isV2Order(LibOrder.Order memory order) internal pure returns (bool) { return order.makerFeeAssetData.length > 3 && order.makerFeeAssetData.readBytes4(0) == EXCHANGE_V2_ORDER_ID; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinReceiver { bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; /// @notice Handle the receipt of a single ERC1155 token type /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the ///transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param id An array containing the ids of the token being transferred /// @param value An array containing the amount of tokens being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4) { return ERC1155_RECEIVED; } /// @notice Handle the receipt of multiple ERC1155 token types /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param ids An array containing ids of each token being transferred /// @param values An array containing amounts of each token being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4) { return ERC1155_BATCH_RECEIVED; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IForwarder { /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes calldata assetData, uint256 amount ) external; } contract Forwarder is IForwarder, Ownable, MixinWethUtils, MixinExchangeWrapper, MixinReceiver { using LibBytes for bytes; using LibAssetDataTransfer for bytes; using LibSafeMath for uint256; constructor ( address _exchange, address _exchangeV2, address _weth ) public Ownable() MixinWethUtils( _exchange, _weth ) MixinExchangeWrapper( _exchange, _exchangeV2 ) {} // solhint-disable-line no-empty-blocks /// @dev Withdraws assets from this contract. It may be used by the owner to withdraw assets /// that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of the asset to withdraw. function withdrawAsset( bytes calldata assetData, uint256 amount ) external onlyOwner { assetData.transferOut(amount); } // maker lists NFT for x eth with this contract address as sender's address and all fees to this contract address . // the 0x order is only fillable via this sender's contract // contract then converts the weth to eth and sends to maker after taking the fees // hardcoded the fee so owner cant arbitarily change fee to anything without timelock function BuyOrderWithEth( LibOrder.Order memory order, uint256 makerAssetBuyAmount, bytes memory signature ) public payable returns ( uint256 wethSpentAmount, uint256 makerAssetAcquiredAmount ) { uint256 fee = 10000; // 1% uint256 feeBase = 1000000; // convert all eth to weth WETH.deposit.value(msg.value)(); // converting to arays for use in _marketBuyFillOrKill function LibOrder.Order[] memory orderarray = new LibOrder.Order[](1); orderarray[0] = order; bytes[] memory signaturearray = new bytes[](1); signaturearray[0] = signature; ( wethSpentAmount, makerAssetAcquiredAmount ) = _marketBuyFillOrKill( orderarray, makerAssetBuyAmount, signaturearray ); // Ensure that no extra WETH owned by this contract has been spent. if (wethSpentAmount > msg.value) { LibRichErrors.rrevert(LibForwarderRichErrors.OverspentWethError( wethSpentAmount, msg.value )); } WETH.withdraw(msg.value); //require(success, "all weth didnt come to this contract"); uint256 ethFeeAmount = wethSpentAmount*fee/feeBase; _transferEthToAddress(ethFeeAmount,owner); _transferEthToAddress(wethSpentAmount.safeSub(ethFeeAmount),order.makerAddress); uint256 wethRemaining = msg.value.safeSub(wethSpentAmount); //dust if (wethRemaining>100000000000000){ msg.sender.transfer(wethRemaining); } } } // https://www.diffchecker.com/mrnWosGS
bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4(keccak256("CompleteBuyFailedError(uint256,uint256)")) bytes4(keccak256("CompleteSellFailedError(uint256,uint256)")) bytes4(keccak256("UnsupportedFeeError(bytes)")) bytes4(keccak256("OverspentWethError(uint256,uint256)")) solhint-disable func-name-mixedcase
library LibForwarderRichErrors { bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; bytes4 internal constant COMPLETE_BUY_FAILED_ERROR_SELECTOR = 0x91353a0c; bytes4 internal constant COMPLETE_SELL_FAILED_ERROR_SELECTOR = 0x450a0219; bytes4 internal constant UNSUPPORTED_FEE_ERROR_SELECTOR = 0x31360af1; bytes4 internal constant OVERSPENT_WETH_ERROR_SELECTOR = 0xcdcbed5d; function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function CompleteBuyFailedError( uint256 expectedAssetBuyAmount, uint256 actualAssetBuyAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_BUY_FAILED_ERROR_SELECTOR, expectedAssetBuyAmount, actualAssetBuyAmount ); } function CompleteSellFailedError( uint256 expectedAssetSellAmount, uint256 actualAssetSellAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_SELL_FAILED_ERROR_SELECTOR, expectedAssetSellAmount, actualAssetSellAmount ); } function UnsupportedFeeError( bytes memory takerFeeAssetData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UNSUPPORTED_FEE_ERROR_SELECTOR, takerFeeAssetData ); } function OverspentWethError( uint256 wethSpent, uint256 msgValue ) internal pure returns (bytes memory) { return abi.encodeWithSelector( OVERSPENT_WETH_ERROR_SELECTOR, wethSpent, msgValue ); } }
567,336
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 984, 14327, 6672, 3886, 668, 10031, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 6322, 38, 9835, 2925, 668, 12, 11890, 5034, 16, 11890, 5034, 2225, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 6322, 55, 1165, 2925, 668, 12, 11890, 5034, 16, 11890, 5034, 2225, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 8544, 14667, 668, 12, 3890, 2225, 3719, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 51, 2496, 84, 319, 59, 546, 668, 12, 11890, 5034, 16, 11890, 5034, 2225, 3719, 3704, 11317, 17, 8394, 1326, 17, 529, 17, 19562, 3593, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 10560, 30839, 22591, 4229, 288, 203, 203, 565, 1731, 24, 2713, 5381, 5019, 27511, 2056, 67, 3033, 4043, 67, 16085, 67, 3589, 67, 4803, 916, 273, 203, 3639, 374, 5841, 23, 70, 10525, 70, 28, 72, 31, 203, 203, 565, 1731, 24, 2713, 5381, 25623, 67, 3000, 61, 67, 11965, 67, 3589, 67, 4803, 916, 273, 203, 3639, 374, 92, 29, 3437, 8643, 69, 20, 71, 31, 203, 203, 565, 1731, 24, 2713, 5381, 25623, 67, 1090, 4503, 67, 11965, 67, 3589, 67, 4803, 916, 273, 203, 3639, 374, 92, 24, 3361, 69, 3103, 3657, 31, 203, 203, 565, 1731, 24, 2713, 5381, 26049, 3079, 14289, 67, 8090, 41, 67, 3589, 67, 4803, 916, 273, 203, 3639, 374, 92, 23, 3437, 4848, 1727, 21, 31, 203, 203, 565, 1731, 24, 2713, 5381, 22577, 3118, 2222, 67, 59, 1584, 44, 67, 3589, 67, 4803, 916, 273, 203, 3639, 374, 92, 4315, 71, 2992, 25, 72, 31, 203, 203, 565, 445, 1351, 14327, 6672, 3886, 668, 1435, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 3778, 13, 203, 203, 203, 565, 288, 203, 3639, 327, 24126, 18, 3015, 1190, 4320, 12, 2124, 27511, 2056, 67, 3033, 4043, 67, 16085, 67, 3589, 67, 4803, 916, 1769, 203, 565, 289, 203, 203, 565, 445, 14575, 38, 9835, 2925, 668, 12, 203, 3639, 2254, 5034, 2665, 6672, 38, 9835, 6275, 16, 203, 3639, 2254, 5034, 3214, 6672, 38, 9835, 6275, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 3778, 2 ]
./partial_match/3/0xD675a50E477c035BCAA8191a9715306640683732/sources/Lock.sol
check the mode of this user based on the mode decide denominator - 1 = 30 days 2= 1 week 3 = 1 day Calculate difference between now and end date
function _pendingClaim(uint256 id) internal view returns(uint256 _pendingAmount){ LockedAsset storage asset = _idVsLockedAsset[id]; uint256 pendingAmount; if(asset.claimMode == 1 || asset.claimMode == 2 || asset.claimMode == 3){ uint256 denominator; denominator = 30 days; denominator = 7 days; else if(asset.claimMode == 3) uint256 difference = 0; if(block.timestamp > asset.releaseDate){ difference= block.timestamp.sub(asset.endDate); else difference = block.timestamp.sub(asset.lastClaimedDate); } if(totalPercentage > 100) totalPercentage = 100; pendingAmount = totalPercentage.mul(onePercent((asset.amount).sub(asset.claimed))); pendingAmount = pendingAmount; pendingAmount = asset.amount; } return (pendingAmount); }
5,119,594
[ 1, 1893, 326, 1965, 434, 333, 729, 2511, 603, 326, 1965, 16288, 15030, 300, 404, 273, 5196, 4681, 576, 33, 404, 4860, 890, 273, 404, 2548, 9029, 7114, 3086, 2037, 471, 679, 1509, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 9561, 9762, 12, 11890, 5034, 612, 13, 2713, 1476, 1135, 12, 11890, 5034, 389, 9561, 6275, 15329, 203, 3639, 3488, 329, 6672, 2502, 3310, 273, 389, 350, 16082, 8966, 6672, 63, 350, 15533, 203, 3639, 2254, 5034, 4634, 6275, 31, 203, 3639, 309, 12, 9406, 18, 14784, 2309, 422, 404, 747, 3310, 18, 14784, 2309, 422, 576, 747, 3310, 18, 14784, 2309, 422, 890, 15329, 203, 5411, 2254, 5034, 15030, 31, 203, 540, 203, 540, 203, 7734, 15030, 273, 5196, 4681, 31, 203, 7734, 15030, 273, 2371, 4681, 31, 203, 5411, 469, 309, 12, 9406, 18, 14784, 2309, 422, 890, 13, 203, 2398, 203, 5411, 2254, 5034, 7114, 273, 374, 31, 203, 5411, 309, 12, 2629, 18, 5508, 405, 3310, 18, 9340, 1626, 15329, 203, 10792, 7114, 33, 1203, 18, 5508, 18, 1717, 12, 9406, 18, 409, 1626, 1769, 203, 7734, 469, 203, 10792, 7114, 273, 1203, 18, 5508, 18, 1717, 12, 9406, 18, 2722, 9762, 329, 1626, 1769, 203, 5411, 289, 203, 2398, 203, 2398, 203, 5411, 309, 12, 4963, 16397, 405, 2130, 13, 203, 7734, 2078, 16397, 273, 2130, 31, 203, 1171, 203, 5411, 4634, 6275, 273, 2078, 16397, 18, 16411, 12, 476, 8410, 12443, 9406, 18, 8949, 2934, 1717, 12, 9406, 18, 14784, 329, 3719, 1769, 203, 2398, 203, 5411, 4634, 6275, 273, 4634, 6275, 31, 203, 2398, 203, 5411, 4634, 6275, 273, 3310, 18, 8949, 31, 203, 3639, 289, 203, 3639, 327, 261, 9561, 6275, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // ChargedState.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IChargedState.sol"; import "./lib/Bitwise.sol"; import "./lib/TokenInfo.sol"; import "./lib/RelayRecipient.sol"; import "./lib/BlackholePrevention.sol"; /** * @notice Charged Particles Settings Contract */ contract ChargedState is IChargedState, Ownable, RelayRecipient, BlackholePrevention { using SafeMath for uint256; using TokenInfo for address; using Bitwise for uint32; // NftState - actionPerms uint32 constant internal PERM_RESTRICT_ENERGIZE_FROM_ALL = 1; // NFTs that have Restrictions on Energize uint32 constant internal PERM_ALLOW_DISCHARGE_FROM_ALL = 2; // NFTs that allow Discharge by anyone uint32 constant internal PERM_ALLOW_RELEASE_FROM_ALL = 4; // NFTs that allow Release by anyone uint32 constant internal PERM_RESTRICT_BOND_FROM_ALL = 8; // NFTs that have Restrictions on Covalent Bonds uint32 constant internal PERM_ALLOW_BREAK_BOND_FROM_ALL = 16; // NFTs that allow Breaking Covalent Bonds by anyone struct NftTimelock { uint256 unlockBlock; address lockedBy; } struct NftState { uint32 actionPerms; NftTimelock dischargeTimelock; NftTimelock releaseTimelock; NftTimelock breakBondTimelock; uint256 tempLockExpiry; mapping (address => address) dischargeApproval; mapping (address => address) releaseApproval; mapping (address => address) breakBondApproval; mapping (address => address) timelockApproval; } IChargedSettings internal _chargedSettings; // State of individual NFTs (by Token UUID) mapping (uint256 => NftState) internal _nftState; /***********************************| | Public | |__________________________________*/ function getDischargeTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].dischargeTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].dischargeTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } function getReleaseTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].releaseTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].releaseTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } function getBreakBondTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].breakBondTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].breakBondTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } /// @notice Checks if an operator is allowed to Discharge a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForDischarge(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Release a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForRelease(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Break Covalent Bonds on a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForBreakBond(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Timelock a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForTimelock(contractAddress, tokenId, operator); } function isEnergizeRestricted(address contractAddress, uint256 tokenId) external virtual override view returns (bool) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return _nftState[tokenUuid].actionPerms.hasBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } function isCovalentBondRestricted(address contractAddress, uint256 tokenId) external virtual override view returns (bool) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return _nftState[tokenUuid].actionPerms.hasBit(PERM_RESTRICT_BOND_FROM_ALL); } function getDischargeState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_DISCHARGE_FROM_ALL); isApproved = _isApprovedForDischarge(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].dischargeTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } function getReleaseState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_RELEASE_FROM_ALL); isApproved = _isApprovedForRelease(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].releaseTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } function getBreakBondState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); isApproved = _isApprovedForBreakBond(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].breakBondTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } /***********************************| | Only NFT Owner/Operator | |__________________________________*/ /// @notice Sets an Operator as Approved to Discharge a specific Token /// This allows an operator to withdraw the interest-portion only /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setDischargeApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setDischargeApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Release a specific Token /// This allows an operator to withdraw the principal + interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setReleaseApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setReleaseApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Break Covalent Bonds on a specific Token /// This allows an operator to withdraw Basket NFTs /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setBreakBondApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setBreakBondApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Timelock a specific Token /// This allows an operator to timelock the principal or interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setTimelockApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setTimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Discharge/Release/Timelock a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setApprovalForAll( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setDischargeApproval(contractAddress, tokenId, tokenOwner, operator); _setReleaseApproval(contractAddress, tokenId, tokenOwner, operator); _setBreakBondApproval(contractAddress, tokenId, tokenOwner, operator); _setTimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @dev Updates Restrictions on Energizing an NFT function setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForRestrictCharge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowDischarge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowRelease(contractAddress, tokenId, state); } /// @dev Updates Restrictions on Covalent Bonds on an NFT function setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForRestrictBond(contractAddress, tokenId, state); } /// @dev Updates Allowance on Breaking Covalent Bonds on an NFT by Anyone function setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowBreakBond(contractAddress, tokenId, state); } /// @notice Sets a Timelock on the ability to Discharge the Interest of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setDischargeTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].dischargeTimelock.lockedBy == sender) { delete _nftState[tokenUuid].dischargeTimelock.unlockBlock; delete _nftState[tokenUuid].dischargeTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].dischargeTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].dischargeTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].dischargeTimelock.lockedBy = sender; } emit TokenDischargeTimelock(contractAddress, tokenId, sender, unlockBlock); } /// @notice Sets a Timelock on the ability to Release the Assets of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setReleaseTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].releaseTimelock.lockedBy == sender) { delete _nftState[tokenUuid].releaseTimelock.unlockBlock; delete _nftState[tokenUuid].releaseTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].releaseTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].releaseTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].releaseTimelock.lockedBy = sender; } emit TokenReleaseTimelock(contractAddress, tokenId, sender, unlockBlock); } /// @notice Sets a Timelock on the ability to Break the Covalent Bond of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setBreakBondTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].breakBondTimelock.lockedBy == sender) { delete _nftState[tokenUuid].breakBondTimelock.unlockBlock; delete _nftState[tokenUuid].breakBondTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].breakBondTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].breakBondTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].breakBondTimelock.lockedBy = sender; } emit TokenBreakBondTimelock(contractAddress, tokenId, sender, unlockBlock); } /***********************************| | Only NFT Contract | |__________________________________*/ /// @notice Sets a Temporary-Lock on the ability to Release/Discharge the Assets of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param isLocked The locked state; contracts are expected to disable this lock before expiry function setTemporaryLock( address contractAddress, uint256 tokenId, bool isLocked ) external override virtual { require(msg.sender == contractAddress, "CP:E-112"); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); uint256 unlockBlock; if (isLocked && _nftState[tokenUuid].tempLockExpiry == 0) { unlockBlock = block.number.add(_chargedSettings.getTempLockExpiryBlocks()); _nftState[tokenUuid].tempLockExpiry = unlockBlock; } if (!isLocked) { _nftState[tokenUuid].tempLockExpiry = 0; } emit TokenTempLock(contractAddress, tokenId, unlockBlock); } /***********************************| | Only Admin/DAO | |__________________________________*/ /// @dev Setup the Charged-Settings Controller function setChargedSettings(address settingsController) external virtual onlyOwner { _chargedSettings = IChargedSettings(settingsController); emit ChargedSettingsSet(settingsController); } function setTrustedForwarder(address _trustedForwarder) external onlyOwner { trustedForwarder = _trustedForwarder; } /***********************************| | Only Admin/DAO | | (blackhole prevention) | |__________________________________*/ function withdrawEther(address payable receiver, uint256 amount) external virtual onlyOwner { _withdrawEther(receiver, amount); } function withdrawErc20(address payable receiver, address tokenAddress, uint256 amount) external virtual onlyOwner { _withdrawERC20(receiver, tokenAddress, amount); } function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external virtual onlyOwner { _withdrawERC721(receiver, tokenAddress, tokenId); } /***********************************| | Private Functions | |__________________________________*/ /// @dev See {ChargedParticles-isApprovedForDischarge}. function _isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].dischargeApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForRelease}. function _isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].releaseApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForBreakBond}. function _isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].breakBondApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForTimelock}. function _isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { (bool timelockAny, bool timelockOwn) = _chargedSettings.getTimelockApprovals(operator); if (timelockAny || (timelockOwn && contractAddress == operator)) { return true; } address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return tokenOwner == operator || _nftState[tokenUuid].timelockApproval[tokenOwner] == operator; } /// @notice Sets an Operator as Approved to Discharge a specific Token /// This allows an operator to withdraw the interest-portion only /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setDischargeApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].dischargeApproval[tokenOwner] = operator; emit DischargeApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Release a specific Token /// This allows an operator to withdraw the principal + interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setReleaseApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].releaseApproval[tokenOwner] = operator; emit ReleaseApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Break Covalent Bonds on a specific Token /// This allows an operator to withdraw Basket NFTs /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setBreakBondApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].breakBondApproval[tokenOwner] = operator; emit BreakBondApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Timelock a specific Token /// This allows an operator to timelock the principal or interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setTimelockApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].timelockApproval[tokenOwner] = operator; emit TimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @dev Updates Restrictions on Energizing an NFT function _setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } emit PermsSetForRestrictCharge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function _setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_DISCHARGE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_DISCHARGE_FROM_ALL); } emit PermsSetForAllowDischarge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function _setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_RELEASE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_RELEASE_FROM_ALL); } emit PermsSetForAllowRelease(contractAddress, tokenId, state); } /// @dev Updates Restrictions on Covalent Bonds on an NFT function _setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_RESTRICT_BOND_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_RESTRICT_BOND_FROM_ALL); } emit PermsSetForRestrictBond(contractAddress, tokenId, state); } /// @dev Updates Allowance on Breaking Covalent Bonds on an NFT by Anyone function _setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); } emit PermsSetForAllowBreakBond(contractAddress, tokenId, state); } /***********************************| | GSN/MetaTx Relay | |__________________________________*/ /// @dev See {BaseRelayRecipient-_msgSender}. function _msgSender() internal view virtual override(BaseRelayRecipient, Context) returns (address payable) { return BaseRelayRecipient._msgSender(); } /// @dev See {BaseRelayRecipient-_msgData}. function _msgData() internal view virtual override(BaseRelayRecipient, Context) returns (bytes memory) { return BaseRelayRecipient._msgData(); } /***********************************| | Modifiers | |__________________________________*/ modifier onlyErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) { require(contractAddress.isErc721OwnerOrOperator(tokenId, sender), "CP:E-105"); _; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // IChargedSettings.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; import "./IChargedSettings.sol"; /** * @notice Interface for Charged State */ interface IChargedState { /***********************************| | Public API | |__________________________________*/ function getDischargeTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function getReleaseTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function getBreakBondTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isEnergizeRestricted(address contractAddress, uint256 tokenId) external view returns (bool); function isCovalentBondRestricted(address contractAddress, uint256 tokenId) external view returns (bool); function getDischargeState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); function getReleaseState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); function getBreakBondState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); /***********************************| | Only NFT Owner/Operator | |__________________________________*/ function setDischargeApproval(address contractAddress, uint256 tokenId, address operator) external; function setReleaseApproval(address contractAddress, uint256 tokenId, address operator) external; function setBreakBondApproval(address contractAddress, uint256 tokenId, address operator) external; function setTimelockApproval(address contractAddress, uint256 tokenId, address operator) external; function setApprovalForAll(address contractAddress, uint256 tokenId, address operator) external; function setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) external; function setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) external; function setDischargeTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setReleaseTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setBreakBondTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; /***********************************| | Only NFT Contract | |__________________________________*/ function setTemporaryLock( address contractAddress, uint256 tokenId, bool isLocked ) external; /***********************************| | Particle Events | |__________________________________*/ event ChargedSettingsSet(address indexed settingsController); event DischargeApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event ReleaseApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event BreakBondApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event TimelockApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event TokenDischargeTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenReleaseTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenBreakBondTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenTempLock(address indexed contractAddress, uint256 indexed tokenId, uint256 unlockBlock); event PermsSetForRestrictCharge(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowDischarge(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowRelease(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForRestrictBond(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowBreakBond(address indexed contractAddress, uint256 indexed tokenId, bool state); } // SPDX-License-Identifier: MIT // Bitwise.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.12; library Bitwise { function negate(uint32 a) internal pure returns (uint32) { return a ^ maxInt(); } function shiftLeft(uint32 a, uint32 n) internal pure returns (uint32) { return a * uint32(2) ** n; } function shiftRight(uint32 a, uint32 n) internal pure returns (uint32) { return a / uint32(2) ** n; } function maxInt() internal pure returns (uint32) { return uint32(-1); } // Get bit value at position function hasBit(uint32 a, uint32 n) internal pure returns (bool) { return a & shiftLeft(0x01, n) != 0; } // Set bit value at position function setBit(uint32 a, uint32 n) internal pure returns (uint32) { return a | shiftLeft(0x01, n); } // Set the bit into state "false" function clearBit(uint32 a, uint32 n) internal pure returns (uint32) { uint32 mask = negate(shiftLeft(0x01, n)); return a & mask; } } // SPDX-License-Identifier: MIT // TokenInfo.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../interfaces/IERC721Chargeable.sol"; library TokenInfo { function getTokenUUID(address contractAddress, uint256 tokenId) internal pure virtual returns (uint256) { return uint256(keccak256(abi.encodePacked(contractAddress, tokenId))); } function getTokenOwner(address contractAddress, uint256 tokenId) internal view virtual returns (address) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); return tokenInterface.ownerOf(tokenId); } function getTokenCreator(address contractAddress, uint256 tokenId) internal view virtual returns (address) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); return tokenInterface.creatorOf(tokenId); } /// @dev Checks if an account is the Owner of an External NFT contract /// @param contractAddress The Address to the Contract of the NFT to check /// @param account The Address of the Account to check /// @return True if the account owns the contract function isContractOwner(address contractAddress, address account) internal view virtual returns (bool) { address contractOwner = IERC721Chargeable(contractAddress).owner(); return contractOwner != address(0x0) && contractOwner == account; } /// @dev Checks if an account is the Creator of a Proton-based NFT /// @param contractAddress The Address to the Contract of the Proton-based NFT to check /// @param tokenId The Token ID of the Proton-based NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the creator of the Proton-based NFT function isTokenCreator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenCreator = tokenInterface.creatorOf(tokenId); return (sender == tokenCreator); } /// @dev Checks if an account is the Creator of a Proton-based NFT or the Contract itself /// @param contractAddress The Address to the Contract of the Proton-based NFT to check /// @param tokenId The Token ID of the Proton-based NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the creator of the Proton-based NFT or the Contract itself function isTokenContractOrCreator(address contractAddress, uint256 tokenId, address creator, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenCreator = tokenInterface.creatorOf(tokenId); if (sender == contractAddress && creator == tokenCreator) { return true; } return (sender == tokenCreator); } /// @dev Checks if an account is the Owner or Operator of an External NFT /// @param contractAddress The Address to the Contract of the External NFT to check /// @param tokenId The Token ID of the External NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the Owner or Operator of the External NFT function isErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenOwner = tokenInterface.ownerOf(tokenId); return (sender == tokenOwner || tokenInterface.isApprovedForAll(tokenOwner, sender)); } /** * @dev Returns true if `account` is a contract. * @dev Taken from OpenZeppelin library * * [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. * @dev Taken from OpenZeppelin library * * 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, "TokenInfo: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "TokenInfo: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; contract RelayRecipient is BaseRelayRecipient { function versionRecipient() external override view returns (string memory) { return "1.0.0-beta.1/charged-particles.relay.recipient"; } } // SPDX-License-Identifier: MIT // BlackholePrevention.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @notice Prevents ETH or Tokens from getting stuck in a contract by allowing * the Owner/DAO to pull them out on behalf of a user * This is only meant to contracts that are not expected to hold tokens, but do handle transferring them. */ contract BlackholePrevention { using Address for address payable; using SafeERC20 for IERC20; event WithdrawStuckEther(address indexed receiver, uint256 amount); event WithdrawStuckERC20(address indexed receiver, address indexed tokenAddress, uint256 amount); event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId); function _withdrawEther(address payable receiver, uint256 amount) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (address(this).balance >= amount) { receiver.sendValue(amount); emit WithdrawStuckEther(receiver, amount); } } function _withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) { IERC20(tokenAddress).safeTransfer(receiver, amount); emit WithdrawStuckERC20(receiver, tokenAddress, amount); } } function _withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) { IERC721(tokenAddress).transferFrom(address(this), receiver, tokenId); emit WithdrawStuckERC721(receiver, tokenAddress, tokenId); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT // IChargedSettings.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; import "./IWalletManager.sol"; import "./IBasketManager.sol"; /** * @notice Interface for Charged Settings */ interface IChargedSettings { /***********************************| | Public API | |__________________________________*/ function isContractOwner(address contractAddress, address account) external view returns (bool); function getCreatorAnnuities(address contractAddress, uint256 tokenId) external view returns (address creator, uint256 annuityPct); function getCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId) external view returns (address); function getTempLockExpiryBlocks() external view returns (uint256); function getTimelockApprovals(address operator) external view returns (bool timelockAny, bool timelockOwn); function getAssetRequirements(address contractAddress, address assetToken) external view returns (string memory requiredWalletManager, bool energizeEnabled, bool restrictedAssets, bool validAsset, uint256 depositCap, uint256 depositMin, uint256 depositMax); function getNftAssetRequirements(address contractAddress, address nftTokenAddress) external view returns (string memory requiredBasketManager, bool basketEnabled, uint256 maxNfts); // ERC20 function isWalletManagerEnabled(string calldata walletManagerId) external view returns (bool); function getWalletManager(string calldata walletManagerId) external view returns (IWalletManager); // ERC721 function isNftBasketEnabled(string calldata basketId) external view returns (bool); function getBasketManager(string calldata basketId) external view returns (IBasketManager); /***********************************| | Only NFT Creator | |__________________________________*/ function setCreatorAnnuities(address contractAddress, uint256 tokenId, address creator, uint256 annuityPercent) external; function setCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId, address creator, address receiver) external; /***********************************| | Only NFT Contract Owner | |__________________________________*/ function setRequiredWalletManager(address contractAddress, string calldata walletManager) external; function setRequiredBasketManager(address contractAddress, string calldata basketManager) external; function setAssetTokenRestrictions(address contractAddress, bool restrictionsEnabled) external; function setAllowedAssetToken(address contractAddress, address assetToken, bool isAllowed) external; function setAssetTokenLimits(address contractAddress, address assetToken, uint256 depositMin, uint256 depositMax) external; function setMaxNfts(address contractAddress, address nftTokenAddress, uint256 maxNfts) external; /***********************************| | Only Admin/DAO | |__________________________________*/ function enableNftContracts(address[] calldata contracts) external; function setPermsForCharge(address contractAddress, bool state) external; function setPermsForBasket(address contractAddress, bool state) external; function setPermsForTimelockAny(address contractAddress, bool state) external; function setPermsForTimelockSelf(address contractAddress, bool state) external; /***********************************| | Particle Events | |__________________________________*/ event DepositCapSet(address assetToken, uint256 depositCap); event TempLockExpirySet(uint256 expiryBlocks); event WalletManagerRegistered(string indexed walletManagerId, address indexed walletManager); event BasketManagerRegistered(string indexed basketId, address indexed basketManager); event RequiredWalletManagerSet(address indexed contractAddress, string walletManager); event RequiredBasketManagerSet(address indexed contractAddress, string basketManager); event AssetTokenRestrictionsSet(address indexed contractAddress, bool restrictionsEnabled); event AllowedAssetTokenSet(address indexed contractAddress, address assetToken, bool isAllowed); event AssetTokenLimitsSet(address indexed contractAddress, address assetToken, uint256 assetDepositMin, uint256 assetDepositMax); event MaxNftsSet(address indexed contractAddress, address indexed nftTokenAddress, uint256 maxNfts); event TokenCreatorConfigsSet(address indexed contractAddress, uint256 indexed tokenId, address indexed creatorAddress, uint256 annuityPercent); event TokenCreatorAnnuitiesRedirected(address indexed contractAddress, uint256 indexed tokenId, address indexed redirectAddress); event PermsSetForCharge(address indexed contractAddress, bool state); event PermsSetForBasket(address indexed contractAddress, bool state); event PermsSetForTimelockAny(address indexed contractAddress, bool state); event PermsSetForTimelockSelf(address indexed contractAddress, bool state); } // SPDX-License-Identifier: MIT // IWalletManager.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; /** * @title Particle Wallet Manager interface * @dev The wallet-manager for underlying assets attached to Charged Particles * @dev Manages the link between NFTs and their respective Smart-Wallets */ interface IWalletManager { event ControllerSet(address indexed controller); event PausedStateSet(bool isPaused); event NewSmartWallet(address indexed contractAddress, uint256 indexed tokenId, address indexed smartWallet, address creator, uint256 annuityPct); event WalletEnergized(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 assetAmount, uint256 yieldTokensAmount); event WalletDischarged(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 creatorAmount, uint256 receiverAmount); event WalletDischargedForCreator(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, address creator, uint256 receiverAmount); event WalletReleased(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address assetToken, uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); event WalletRewarded(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address rewardsToken, uint256 rewardsAmount); function isPaused() external view returns (bool); function isReserveActive(address contractAddress, uint256 tokenId, address assetToken) external view returns (bool); function getReserveInterestToken(address contractAddress, uint256 tokenId, address assetToken) external view returns (address); function getTotal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256); function getPrincipal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256); function getInterest(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256 creatorInterest, uint256 ownerInterest); function getRewards(address contractAddress, uint256 tokenId, address rewardToken) external returns (uint256); function energize(address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount) external returns (uint256 yieldTokensAmount); function discharge(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeAmountForCreator(address receiver, address contractAddress, uint256 tokenId, address creator, address assetToken, uint256 assetAmount) external returns (uint256 receiverAmount); function release(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); function releaseAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); function withdrawRewards(address receiver, address contractAddress, uint256 tokenId, address rewardsToken, uint256 rewardsAmount) external returns (uint256 amount); function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory); function getWalletAddressById(address contractAddress, uint256 tokenId, address creator, uint256 annuityPct) external returns (address); function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external; function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external; function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external; } // SPDX-License-Identifier: MIT // IBasketManager.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; /** * @title Particle Basket Manager interface * @dev The basket-manager for underlying assets attached to Charged Particles * @dev Manages the link between NFTs and their respective Smart-Baskets */ interface IBasketManager { event ControllerSet(address indexed controller); event PausedStateSet(bool isPaused); event NewSmartBasket(address indexed contractAddress, uint256 indexed tokenId, address indexed smartBasket); event BasketAdd(address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId); event BasketRemove(address indexed receiver, address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId); function isPaused() external view returns (bool); function getTokenTotalCount(address contractAddress, uint256 tokenId) external view returns (uint256); function getTokenCountByType(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (uint256); function addToBasket(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool); function removeFromBasket(address receiver, address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool); function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory); function getBasketAddressById(address contractAddress, uint256 tokenId) external returns (address); function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external; function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external; function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // IERC721Chargeable.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // 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 NON-INFRINGEMENT. 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.6.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; interface IERC721Chargeable is IERC165Upgradeable { function owner() external view returns (address); function creatorOf(uint256 tokenId) external view returns (address); function balanceOf(address tokenOwner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address tokenOwner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address tokenOwner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 // solhint-disable no-inline-assembly pragma solidity ^0.6.2; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(),20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr,32), size) calldatacopy(add(ptr,64), 0, size) return(ptr, add(size,64)) } } else { return msg.data; } } } // SPDX-License-Identifier:MIT pragma solidity ^0.6.2; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT 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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); }
Get bit value at position
function hasBit(uint32 a, uint32 n) internal pure returns (bool) { return a & shiftLeft(0x01, n) != 0; }
354,565
[ 1, 967, 2831, 460, 622, 1754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 711, 5775, 12, 11890, 1578, 279, 16, 2254, 1578, 290, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 565, 327, 279, 473, 4654, 3910, 12, 20, 92, 1611, 16, 290, 13, 480, 374, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-30 */ // File: contracts/math/SafeMath.sol pragma solidity 0.5.12; /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { /// @dev Add two integers function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; //assert(c >= a); return c; } /// @dev Subtract two integers function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /// @dev Multiply tow integers function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /// @dev Floor divide two integers function div(uint a, uint b) internal pure returns (uint) { return a / b; } } // File: contracts/ownership/Ownable.sol pragma solidity 0.5.12; /// @title Ownable /// @dev Provide a simple access control with a single authority: the owner contract Ownable { // Ethereum address of current owner address public owner; // Ethereum address of the next owner // (has to claim ownership first to become effective owner) address public newOwner; // @dev Log event on ownership transferred // @param previousOwner Ethereum address of previous owner // @param newOwner Ethereum address of new owner event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Forbid call by anyone but owner modifier onlyOwner() { require(msg.sender == owner, "Restricted to owner"); _; } /// @dev Deployer account becomes initial owner constructor() public { owner = msg.sender; } /// @dev Transfer ownership to a new Ethereum account (safe method) /// Note: the new owner has to claim his ownership to become effective owner. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); newOwner = _newOwner; } /// @dev Transfer ownership to a new Ethereum account (unsafe method) /// Note: It's strongly recommended to use the safe variant via transferOwnership /// and claimOwnership, to prevent accidental transfers to a wrong address. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnershipUnsafe(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); _transferOwnership(_newOwner); } /// @dev Become effective owner (if dedicated so by previous owner) function claimOwnership() public { require(msg.sender == newOwner, "Restricted to new owner"); _transferOwnership(msg.sender); } /// @dev Transfer ownership (internal method) /// @param _newOwner Ethereum address to transfer ownership to function _transferOwnership(address _newOwner) private { if (_newOwner != owner) { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } newOwner = address(0x0); } } // File: contracts/whitelist/Whitelist.sol pragma solidity 0.5.12; /// @title Whitelist /// @author STOKR contract Whitelist is Ownable { // Set of admins mapping(address => bool) public admins; // Set of Whitelisted addresses mapping(address => bool) public isWhitelisted; /// @dev Log entry on admin added to set /// @param admin An Ethereum address event AdminAdded(address indexed admin); /// @dev Log entry on admin removed from set /// @param admin An Ethereum address event AdminRemoved(address indexed admin); /// @dev Log entry on investor added set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorAdded(address indexed admin, address indexed investor); /// @dev Log entry on investor removed from set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorRemoved(address indexed admin, address indexed investor); /// @dev Only admin modifier onlyAdmin() { require(admins[msg.sender], "Restricted to whitelist admin"); _; } /// @dev Add admin to set /// @param _admin An Ethereum address function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } /// @dev Remove admin from set /// @param _admin An Ethereum address function removeAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary? if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } /// @dev Add investor to set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } /// @dev Remove investor from set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } } // File: contracts/whitelist/Whitelisted.sol pragma solidity 0.5.12; /// @title Whitelisted /// @author STOKR contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } } // File: contracts/token/ERC20.sol pragma solidity 0.5.12; /// @title ERC20 interface /// @dev see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); 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); } // File: contracts/token/ProfitSharing.sol pragma solidity 0.5.12; /// @title ProfitSharing /// @author STOKR contract ProfitSharing is Ownable { using SafeMath for uint; // An InvestorAccount object keeps track of the investor's // - balance: amount of tokens he/she holds (always up-to-date) // - profitShare: amount of wei this token owed him/her at the last update // - lastTotalProfits: determines when his/her profitShare was updated // Note, this construction requires: // - totalProfits to never decrease // - totalSupply to be fixed // - profitShare of all involved parties to get updated prior to any token transfer // - lastTotalProfits to be set to current totalProfits upon profitShare update struct InvestorAccount { uint balance; // token balance uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update uint profitShare; // profit share [wei] of last update } // Investor account database mapping(address => InvestorAccount) public accounts; // Authority who is allowed to deposit profits [wei] on this address public profitDepositor; // Authority who is allowed to distribute profit shares [wei] to investors // (so, that they don't need to withdraw it by themselves) address public profitDistributor; // Amount of total profits [wei] stored to this token // In contrast to the wei balance (which may be reduced due to profit share withdrawal) // this value will never decrease uint public totalProfits; // As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air, // the investors' profit shares aren't determined bool public totalSupplyIsFixed; // Total amount of tokens uint internal totalSupply_; /// @dev Log entry on change of profit deposit authority /// @param previous Ethereum address of previous profit depositor /// @param current Ethereum address of new profit depositor event ProfitDepositorChange( address indexed previous, address indexed current ); /// @dev Log entry on change of profit distribution authority /// @param previous Ethereum address of previous profit distributor /// @param current Ethereum address of new profit distributor event ProfitDistributorChange( address indexed previous, address indexed current ); /// @dev Log entry on profit deposit /// @param depositor Profit depositor's address /// @param amount Deposited profits in wei event ProfitDeposit( address indexed depositor, uint amount ); /// @dev Log entry on profit share update /// @param investor Investor's address /// @param amount New wei amount the token owes the investor event ProfitShareUpdate( address indexed investor, uint amount ); /// @dev Log entry on profit withdrawal /// @param investor Investor's address /// @param amount Wei amount the investor withdrew from this token event ProfitShareWithdrawal( address indexed investor, address indexed beneficiary, uint amount ); /// @dev Restrict operation to profit deposit authority only modifier onlyProfitDepositor() { require(msg.sender == profitDepositor, "Restricted to profit depositor"); _; } /// @dev Restrict operation to profit distribution authority only modifier onlyProfitDistributor() { require(msg.sender == profitDistributor, "Restricted to profit distributor"); _; } /// @dev Restrict operation to when total supply doesn't change anymore modifier onlyWhenTotalSupplyIsFixed() { require(totalSupplyIsFixed, "Total supply may change"); _; } /// @dev Constructor /// @param _profitDepositor Profit deposit authority constructor(address _profitDepositor, address _profitDistributor) public { setProfitDepositor(_profitDepositor); setProfitDistributor(_profitDistributor); } /// @dev Profit deposit if possible via fallback function function () external payable { require(msg.data.length == 0, "Fallback call with data"); depositProfit(); } /// @dev Change profit depositor /// @param _newProfitDepositor An Ethereum address function setProfitDepositor(address _newProfitDepositor) public onlyOwner { require(_newProfitDepositor != address(0x0), "New profit depositor is zero"); if (_newProfitDepositor != profitDepositor) { emit ProfitDepositorChange(profitDepositor, _newProfitDepositor); profitDepositor = _newProfitDepositor; } } /// @dev Change profit distributor /// @param _newProfitDistributor An Ethereum address function setProfitDistributor(address _newProfitDistributor) public onlyOwner { require(_newProfitDistributor != address(0x0), "New profit distributor is zero"); if (_newProfitDistributor != profitDistributor) { emit ProfitDistributorChange(profitDistributor, _newProfitDistributor); profitDistributor = _newProfitDistributor; } } /// @dev Deposit profit function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed { require(totalSupply_ > 0, "Total supply is zero"); totalProfits = totalProfits.add(msg.value); emit ProfitDeposit(msg.sender, msg.value); } /// @dev Profit share owing /// @param _investor An Ethereum address /// @return A positive number function profitShareOwing(address _investor) public view returns (uint) { if (!totalSupplyIsFixed || totalSupply_ == 0) { return 0; } InvestorAccount memory account = accounts[_investor]; return totalProfits.sub(account.lastTotalProfits) .mul(account.balance) .div(totalSupply_) .add(account.profitShare); } /// @dev Update profit share /// @param _investor An Ethereum address function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed { uint newProfitShare = profitShareOwing(_investor); accounts[_investor].lastTotalProfits = totalProfits; accounts[_investor].profitShare = newProfitShare; emit ProfitShareUpdate(_investor, newProfitShare); } /// @dev Withdraw profit share function withdrawProfitShare() public { _withdrawProfitShare(msg.sender, msg.sender); } function withdrawProfitShareTo(address payable _beneficiary) public { _withdrawProfitShare(msg.sender, _beneficiary); } /// @dev Withdraw profit share function withdrawProfitShares(address payable[] calldata _investors) external onlyProfitDistributor { for (uint i = 0; i < _investors.length; ++i) { _withdrawProfitShare(_investors[i], _investors[i]); } } /// @dev Withdraw profit share function _withdrawProfitShare(address _investor, address payable _beneficiary) internal { updateProfitShare(_investor); uint withdrawnProfitShare = accounts[_investor].profitShare; accounts[_investor].profitShare = 0; _beneficiary.transfer(withdrawnProfitShare); emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare); } } // File: contracts/token/MintableToken.sol pragma solidity 0.5.12; /// @title MintableToken /// @author STOKR /// @dev Extension of the ERC20 compliant ProfitSharing Token /// that allows the creation of tokens via minting for a /// limited time period (until minting gets finished). contract MintableToken is ERC20, ProfitSharing, Whitelisted { address public minter; uint public numberOfInvestors = 0; /// @dev Log entry on mint /// @param to Beneficiary who received the newly minted tokens /// @param amount The amount of minted token units event Minted(address indexed to, uint amount); /// @dev Log entry on mint finished event MintFinished(); /// @dev Restrict an operation to be callable only by the minter modifier onlyMinter() { require(msg.sender == minter, "Restricted to minter"); _; } /// @dev Restrict an operation to be executable only while minting was not finished modifier canMint() { require(!totalSupplyIsFixed, "Total supply has been fixed"); _; } /// @dev Set minter authority /// @param _minter Ethereum address of minter authority function setMinter(address _minter) public onlyOwner { require(minter == address(0x0), "Minter has already been set"); require(_minter != address(0x0), "Minter is zero"); minter = _minter; } /// @dev Mint tokens, i.e. create tokens out of thin air /// @param _to Beneficiary who will receive the newly minted tokens /// @param _amount The amount of minted token units function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) { if (accounts[_to].balance == 0) { numberOfInvestors++; } totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Minted(_to, _amount); emit Transfer(address(0x0), _to, _amount); } /// @dev Finish minting -- this should be irreversible function finishMinting() public onlyMinter canMint { totalSupplyIsFixed = true; emit MintFinished(); } } // File: contracts/crowdsale/RateSourceInterface.sol pragma solidity 0.5.12; /// @title RateSource /// @author STOKR interface RateSource { /// @dev The current price of an Ether in EUR cents /// @return Current ether rate function etherRate() external view returns (uint); } // File: contracts/crowdsale/MintingCrowdsale.sol pragma solidity 0.5.12; /// @title MintingCrowdsale /// @author STOKR contract MintingCrowdsale is Ownable { using SafeMath for uint; // Maximum Time of offering period after extension uint constant MAXOFFERINGPERIOD = 80 days; // Ether rate oracle contract providing the price of an Ether in EUR cents RateSource public rateSource; // The token to be sold // In the following, the term "token unit" always refers to the smallest // and non-divisible quantum. Thus, token unit amounts are always integers. // One token is expected to consist of 10^18 token units. MintableToken public token; // Token amounts in token units // The public and the private sale are both capped (i.e. two distinct token pools) // The tokenRemaining variables keep track of how many token units are available // for the respective type of sale uint public tokenCapOfPublicSale; uint public tokenCapOfPrivateSale; uint public tokenRemainingForPublicSale; uint public tokenRemainingForPrivateSale; // Prices are in Euro cents (i.e. 1/100 EUR) uint public tokenPrice; // The minimum amount of tokens a purchaser has to buy via one transaction uint public tokenPurchaseMinimum; // The maximum total amount of tokens a purchaser may buy during start phase uint public tokenPurchaseLimit; // Total token purchased by investor (while purchase amount is limited) mapping(address => uint) public tokenPurchased; // Public sale period uint public openingTime; uint public closingTime; uint public limitEndTime; // Ethereum address where invested funds will be transferred to address payable public companyWallet; // Amount and receiver of reserved tokens uint public tokenReservePerMill; address public reserveAccount; // Wether this crowdsale was finalized or not bool public isFinalized = false; /// @dev Log entry upon token distribution event /// @param beneficiary Ethereum address of token recipient /// @param amount Number of token units /// @param isPublicSale Whether the distribution was via public sale event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale); /// @dev Log entry upon token purchase event /// @param buyer Ethereum address of token purchaser /// @param value Worth in wei of purchased token amount /// @param amount Number of token units event TokenPurchase(address indexed buyer, uint value, uint amount); /// @dev Log entry upon rate change event /// @param previous Previous closing time of sale /// @param current Current closing time of sale event ClosingTimeChange(uint previous, uint current); /// @dev Log entry upon finalization event event Finalization(); /// @dev Constructor /// @param _rateSource Ether rate oracle contract /// @param _token The token to be sold /// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale /// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenPrice Price of a token in EUR cent /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account /// @param _reserveAccount Ethereum address of reserve tokens recipient constructor( RateSource _rateSource, MintableToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public { require(address(_rateSource) != address(0x0), "Rate source is zero"); require(address(_token) != address(0x0), "Token address is zero"); require(_token.minter() == address(0x0), "Token has another minter"); require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero"); require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero"); require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale && _tokenPurchaseMinimum <= _tokenCapOfPrivateSale, "Purchase minimum exceeds cap"); require(_tokenPrice > 0, "Token price is zero"); require(_openingTime >= now, "Opening lies in the past"); require(_closingTime >= _openingTime, "Closing lies before opening"); require(_companyWallet != address(0x0), "Company wallet is zero"); require(_reserveAccount != address(0x0), "Reserve account is zero"); // Note: There are no time related requirements regarding limitEndTime. // If it's below openingTime, token purchases will never be limited. // If it's above closingTime, token purchases will always be limited. if (_limitEndTime > _openingTime) { // But, if there's a purchase limitation phase, the limit must be at // least the purchase minimum or above to make purchases possible. require(_tokenPurchaseLimit >= _tokenPurchaseMinimum, "Purchase limit is below minimum"); } // Utilize safe math to ensure the sum of three token pools does't overflow _tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill); rateSource = _rateSource; token = _token; tokenCapOfPublicSale = _tokenCapOfPublicSale; tokenCapOfPrivateSale = _tokenCapOfPrivateSale; tokenPurchaseMinimum = _tokenPurchaseMinimum; tokenPurchaseLimit= _tokenPurchaseLimit; tokenReservePerMill = _tokenReservePerMill; tokenPrice = _tokenPrice; openingTime = _openingTime; closingTime = _closingTime; limitEndTime = _limitEndTime; companyWallet = _companyWallet; reserveAccount = _reserveAccount; tokenRemainingForPublicSale = _tokenCapOfPublicSale; tokenRemainingForPrivateSale = _tokenCapOfPrivateSale; } /// @dev Fallback function: buys tokens function () external payable { require(msg.data.length == 0, "Fallback call with data"); buyTokens(); } /// @dev Distribute tokens purchased off-chain via public sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPublicSale = distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true); } /// @dev Distribute tokens purchased off-chain via private sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPrivateSale = distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false); } /// @dev Check whether the sale has closed /// @return True iff sale closing time has passed function hasClosed() public view returns (bool) { return now >= closingTime; } /// @dev Check wether the sale is open /// @return True iff sale opening time has passed and sale is not closed yet function isOpen() public view returns (bool) { return now >= openingTime && !hasClosed(); } /// @dev Determine the remaining open time of sale /// @return Time in seconds until sale gets closed, or 0 if sale was closed function timeRemaining() public view returns (uint) { if (hasClosed()) { return 0; } return closingTime - now; } /// @dev Determine the amount of sold tokens (off-chain and on-chain) /// @return Token units amount function tokenSold() public view returns (uint) { return (tokenCapOfPublicSale - tokenRemainingForPublicSale) + (tokenCapOfPrivateSale - tokenRemainingForPrivateSale); } /// @dev Purchase tokens function buyTokens() public payable { require(isOpen(), "Sale is not open"); uint etherRate = rateSource.etherRate(); require(etherRate > 0, "Ether rate is zero"); // Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token] uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low"); // Is the total amount an investor can purchase with Ether limited? if (now < limitEndTime) { uint purchased = tokenPurchased[msg.sender].add(amount); require(purchased <= tokenPurchaseLimit, "Purchase limit reached"); tokenPurchased[msg.sender] = purchased; } tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount); token.mint(msg.sender, amount); forwardFunds(); emit TokenPurchase(msg.sender, msg.value, amount); } /// @dev Extend the offering period of the crowd sale. /// @param _newClosingTime new closingTime of the crowdsale function changeClosingTime(uint _newClosingTime) public onlyOwner { require(!hasClosed(), "Sale has already ended"); require(_newClosingTime > now, "ClosingTime not in the future"); require(_newClosingTime > openingTime, "New offering is zero"); require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long"); emit ClosingTimeChange(closingTime, _newClosingTime); closingTime = _newClosingTime; } /// @dev Finalize, i.e. end token minting phase and enable token transfers function finalize() public onlyOwner { require(!isFinalized, "Sale has already been finalized"); require(hasClosed(), "Sale has not closed"); if (tokenReservePerMill > 0) { token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000)); } token.finishMinting(); isFinalized = true; emit Finalization(); } /// @dev Distribute tokens purchased off-chain (in Euro) to investors /// @param tokenRemaining Token units available for sale /// @param beneficiaries Ethereum addresses of purchasers /// @param amounts Token unit amounts to deliver to each investor /// @return Token units available for sale after distribution function distributeTokens( uint tokenRemaining, address[] memory beneficiaries, uint[] memory amounts, bool isPublicSale ) internal onlyOwner returns (uint) { require(!isFinalized, "Sale has been finalized"); require(beneficiaries.length == amounts.length, "Lengths are different"); for (uint i = 0; i < beneficiaries.length; ++i) { address beneficiary = beneficiaries[i]; uint amount = amounts[i]; require(amount <= tokenRemaining, "Not enough tokens available"); tokenRemaining = tokenRemaining.sub(amount); token.mint(beneficiary, amount); emit TokenDistribution(beneficiary, amount, isPublicSale); } return tokenRemaining; } /// @dev Forward invested ether to company wallet function forwardFunds() internal { companyWallet.transfer(address(this).balance); } } // File: contracts/token/TokenRecoverable.sol pragma solidity 0.5.12; /// @title TokenRecoverable /// @author STOKR contract TokenRecoverable is Ownable { // Address that can do the TokenRecovery address public tokenRecoverer; /// @dev Event emitted when the TokenRecoverer changes /// @param previous Ethereum address of previous token recoverer /// @param current Ethereum address of new token recoverer event TokenRecovererChange(address indexed previous, address indexed current); /// @dev Event emitted in case of a TokenRecovery /// @param oldAddress Ethereum address of old account /// @param newAddress Ethereum address of new account event TokenRecovery(address indexed oldAddress, address indexed newAddress); /// @dev Restrict operation to token recoverer modifier onlyTokenRecoverer() { require(msg.sender == tokenRecoverer, "Restricted to token recoverer"); _; } /// @dev Constructor /// @param _tokenRecoverer Ethereum address of token recoverer constructor(address _tokenRecoverer) public { setTokenRecoverer(_tokenRecoverer); } /// @dev Set token recoverer /// @param _newTokenRecoverer Ethereum address of new token recoverer function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner { require(_newTokenRecoverer != address(0x0), "New token recoverer is zero"); if (_newTokenRecoverer != tokenRecoverer) { emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer); tokenRecoverer = _newTokenRecoverer; } } /// @dev Recover token /// @param _oldAddress address /// @param _newAddress address function recoverToken(address _oldAddress, address _newAddress) public; } // File: contracts/token/StokrToken.sol pragma solidity 0.5.12; /// @title StokrToken /// @author Stokr contract StokrToken is MintableToken, TokenRecoverable { string public name; string public symbol; uint8 public constant decimals = 18; mapping(address => mapping(address => uint)) internal allowance_; /// @dev Log entry on self destruction of the token event TokenDestroyed(); /// @dev Constructor /// @param _whitelist Ethereum address of whitelist contract /// @param _tokenRecoverer Ethereum address of token recoverer constructor( string memory _name, string memory _symbol, Whitelist _whitelist, address _profitDepositor, address _profitDistributor, address _tokenRecoverer ) public Whitelisted(_whitelist) ProfitSharing(_profitDepositor, _profitDistributor) TokenRecoverable(_tokenRecoverer) { name = _name; symbol = _symbol; } /// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached function destruct() public onlyMinter { emit TokenDestroyed(); selfdestruct(address(uint160(owner))); } /// @dev Recover token /// @param _oldAddress address of old account /// @param _newAddress address of new account function recoverToken(address _oldAddress, address _newAddress) public onlyTokenRecoverer onlyWhitelisted(_newAddress) { // Ensure that new address is *not* an existing account. // Check for account.profitShare is not needed because of following implication: // (account.lastTotalProfits == 0) ==> (account.profitShare == 0) require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0, "New address exists already"); updateProfitShare(_oldAddress); accounts[_newAddress] = accounts[_oldAddress]; delete accounts[_oldAddress]; emit TokenRecovery(_oldAddress, _newAddress); emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance); } /// @dev Total supply of this token /// @return Token amount function totalSupply() public view returns (uint) { return totalSupply_; } /// @dev Token balance /// @param _investor Ethereum address of token holder /// @return Token amount function balanceOf(address _investor) public view returns (uint) { return accounts[_investor].balance; } /// @dev Allowed token amount a third party trustee may transfer /// @param _investor Ethereum address of token holder /// @param _spender Ethereum address of third party /// @return Allowed token amount function allowance(address _investor, address _spender) public view returns (uint) { return allowance_[_investor][_spender]; } /// @dev Approve a third party trustee to transfer tokens /// Note: additional requirements are enforced within internal function. /// @param _spender Ethereum address of third party /// @param _value Maximum token amount that is allowed to get transferred /// @return Always true function approve(address _spender, uint _value) public returns (bool) { return _approve(msg.sender, _spender, _value); } /// @dev Increase the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Additional token amount that is allowed to get transferred /// @return Always true function increaseAllowance(address _spender, uint _amount) public returns (bool) { require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount)); } /// @dev Decrease the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Reduced token amount that is allowed to get transferred /// @return Always true function decreaseAllowance(address _spender, uint _amount) public returns (bool) { require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount)); } /// @dev Check if a token transfer is possible /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransfer(address _from, address _to, uint _value) public view returns (bool) { return totalSupplyIsFixed && _from != address(0x0) && _to != address(0x0) && _value <= accounts[_from].balance && whitelist.isWhitelisted(_from) && whitelist.isWhitelisted(_to); } /// @dev Check if a token transfer by third party is possible /// @param _spender Ethereum address of third party trustee /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransferFrom(address _spender, address _from, address _to, uint _value) public view returns (bool) { return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender]; } /// @dev Token transfer /// Note: additional requirements are enforces within internal function. /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transfer(address _to, uint _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } /// @dev Token transfer by a third party /// Note: additional requirements are enforces within internal function. /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance"); return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value)) && _transfer(_from, _to, _value); } /// @dev Approve a third party trustee to transfer tokens (internal implementation) /// @param _from Ethereum address of token holder /// @param _spender Ethereum address of third party /// @param _value Maximum token amount the trustee is allowed to transfer /// @return Always true function _approve(address _from, address _spender, uint _value) internal onlyWhitelisted(_from) onlyWhenTotalSupplyIsFixed returns (bool) { allowance_[_from][_spender] = _value; emit Approval(_from, _spender, _value); return true; } /// @dev Token transfer (internal implementation) /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function _transfer(address _from, address _to, uint _value) internal onlyWhitelisted(_from) onlyWhitelisted(_to) onlyWhenTotalSupplyIsFixed returns (bool) { require(_to != address(0x0), "Recipient is zero"); require(_value <= accounts[_from].balance, "Amount exceeds balance"); updateProfitShare(_from); updateProfitShare(_to); accounts[_from].balance = accounts[_from].balance.sub(_value); accounts[_to].balance = accounts[_to].balance.add(_value); emit Transfer(_from, _to, _value); return true; } } // File: contracts/crowdsale/StokrCrowdsale.sol pragma solidity 0.5.12; /// @title StokrCrowdsale /// @author STOKR contract StokrCrowdsale is MintingCrowdsale { // Soft cap in token units uint public tokenGoal; // As long as the goal is not reached funds of purchases are held back // and investments are assigned to investors here to enable a refunding // if the goal is missed upon finalization mapping(address => uint) public investments; // Log entry upon investor refund event event InvestorRefund(address indexed investor, uint value); /// @dev Constructor /// @param _token The token /// @param _tokenCapOfPublicSale Available token units for public sale /// @param _tokenCapOfPrivateSale Available token units for private sale /// @param _tokenGoal Minimum number of sold token units to be successful /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens /// @param _tokenPrice Price of a token in EUR cent /// @param _rateSource Ethereum address of ether rate setting authority /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _reserveAccount An address constructor( RateSource _rateSource, StokrToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenGoal, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public MintingCrowdsale( _rateSource, _token, _tokenCapOfPublicSale, _tokenCapOfPrivateSale, _tokenPurchaseMinimum, _tokenPurchaseLimit, _tokenReservePerMill, _tokenPrice, _openingTime, _closingTime, _limitEndTime, _companyWallet, _reserveAccount ) { require( _tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale, "Goal is not attainable" ); tokenGoal = _tokenGoal; } /// @dev Wether the goal of sold tokens was reached or not /// @return True if the sale can be considered successful function goalReached() public view returns (bool) { return tokenSold() >= tokenGoal; } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function distributeRefunds(address payable[] calldata _investors) external { for (uint i = 0; i < _investors.length; ++i) { refundInvestor(_investors[i]); } } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function claimRefund() public { refundInvestor(msg.sender); } /// @dev Overwritten. Kill the token if goal was missed function finalize() public onlyOwner { super.finalize(); if (!goalReached()) { StokrToken(address(token)).destruct(); } } function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPublicSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPrivateSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } /// @dev Overwritten. Funds are held back until goal was reached function forwardFunds() internal { if (goalReached()) { super.forwardFunds(); } else { investments[msg.sender] = investments[msg.sender].add(msg.value); } } /// @dev Refund an investor if the sale was not successful /// @param _investor Ethereum address of investor function refundInvestor(address payable _investor) internal { require(isFinalized, "Sale has not been finalized"); require(!goalReached(), "Goal was reached"); uint investment = investments[_investor]; if (investment > 0) { investments[_investor] = 0; _investor.transfer(investment); emit InvestorRefund(_investor, investment); } } }
totalProfits [wei] at the time of last profit share update
uint lastTotalProfits;
1,786,934
[ 1, 4963, 626, 18352, 306, 1814, 77, 65, 622, 326, 813, 434, 1142, 450, 7216, 7433, 1089, 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, 3639, 2254, 1142, 5269, 626, 18352, 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, -100, -100, -100, -100 ]
./partial_match/1/0xC7e63B18dEDF226b1C1a7A436953a63c518bd442/sources/walletCache.sol
@notice This public method allows only the wallet deployer to pop pre-cached wallets or create a new one in case there aren't any
function walletCachePop() external onlyWalletDeployer returns (address payable) { if (cachedWallets.length < 1) { cacheWallet(); } address payable wallet = cachedWallets[cachedWallets.length - 1]; cachedWallets.pop(); return wallet; }
4,141,677
[ 1, 2503, 1071, 707, 5360, 1338, 326, 9230, 7286, 264, 358, 1843, 675, 17, 7097, 17662, 2413, 578, 752, 279, 394, 1245, 316, 648, 1915, 11526, 1404, 1281, 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, 9230, 1649, 7049, 1435, 3903, 1338, 16936, 10015, 264, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 309, 261, 7097, 26558, 2413, 18, 2469, 411, 404, 13, 288, 203, 5411, 1247, 16936, 5621, 203, 3639, 289, 203, 203, 3639, 1758, 8843, 429, 9230, 273, 3472, 26558, 2413, 63, 7097, 26558, 2413, 18, 2469, 300, 404, 15533, 203, 3639, 3472, 26558, 2413, 18, 5120, 5621, 203, 203, 3639, 327, 9230, 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 ]
./partial_match/1/0xf6111bBa6Bc77c756d3f15F8e1fCBb02831d5FE3/sources/WPL.sol
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (hasLimitsInTemporary) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradeActivated) { require( _isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapRouter) && to != address(uniswapPair) ) { require( _lastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _lastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedFromMaxTxn[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } automatedMarketMakerPairs[to] && !_isExcludedFromMaxTxn[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } }
3,627,714
[ 1, 270, 8037, 309, 326, 7412, 4624, 353, 3696, 16, 3387, 326, 1203, 11267, 364, 5405, 343, 345, 414, 353, 444, 1493, 4982, 8037, 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 ]
[ 1, 1, 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, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 5332, 12768, 382, 11685, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 20077, 28724, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 14667, 63, 2080, 65, 747, 389, 291, 16461, 1265, 14667, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 7734, 309, 261, 13866, 6763, 1526, 13, 288, 203, 10792, 309, 261, 203, 13491, 358, 480, 3410, 1435, 597, 203, 13491, 358, 480, 1758, 12, 318, 291, 91, 438, 8259, 13, 597, 203, 13491, 358, 480, 1758, 12, 318, 291, 91, 438, 4154, 13, 203, 10792, 262, 288, 203, 13491, 2583, 2 ]
// SPDX-License-Identifier: GPL-3.0-or-later // solhint-disable reason-string, avoid-low-level-calls, const-name-snakecase pragma solidity 0.8.7; import "../interfaces/IStrategy.sol"; import "../interfaces/IUniswapV2Pair.sol"; import "../interfaces/IBentoBoxMinimal.sol"; import "../libraries/UniswapV2Library.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IAnchorRouter { function depositStable(uint256 _amount) external; function redeemStable(uint256 _amount) external; } interface IExchangeRateFeeder { function exchangeRateOf(address _token, bool _simulate) external view returns (uint256); } abstract contract BaseStrategy is IStrategy, Ownable { using SafeERC20 for IERC20; address public immutable strategyToken; address public immutable bentoBox; address public immutable factory; address public immutable bridgeToken; bool public exited; /// @dev After bentobox 'exits' the strategy harvest, skim and withdraw functions can no loner be called uint256 public maxBentoBoxBalance; /// @dev Slippage protection when calling harvest mapping(address => bool) public strategyExecutors; /// @dev EOAs that can execute safeHarvest event LogConvert(address indexed server, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1); event LogSetStrategyExecutor(address indexed executor, bool allowed); /** @param _strategyToken Address of the underlying token the strategy invests. @param _bentoBox BentoBox address. @param _factory SushiSwap factory. @param _bridgeToken An intermedieary token for swapping any rewards into the underlying token. @param _strategyExecutor an EOA that will execute the safeHarvest function. @dev factory and bridgeToken can be address(0) if we don't expect rewards we would need to swap */ constructor( address _strategyToken, address _bentoBox, address _factory, address _bridgeToken, address _strategyExecutor ) { strategyToken = _strategyToken; bentoBox = _bentoBox; factory = _factory; bridgeToken = _bridgeToken; if (_strategyExecutor != address(0)) { strategyExecutors[_strategyExecutor] = true; emit LogSetStrategyExecutor(_strategyExecutor, true); } } //** Strategy implementation: override the following functions: */ /// @notice Invests the underlying asset. /// @param amount The amount of tokens to invest. /// @dev Assume the contract's balance is greater than the amount function _skim(uint256 amount) internal virtual; /// @notice Harvest any profits made and transfer them to address(this) or report a loss /// @param balance The amount of tokens that have been invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. /// @dev amountAdded can be left at 0 when reporting profits (gas savings). /// amountAdded should not reflect any rewards or tokens the strategy received. /// Calcualte the amount added based on what the current deposit is worth. /// (The Base Strategy harvest function accounts for rewards). function _harvest(uint256 balance) internal virtual returns (int256 amountAdded); /// @dev Withdraw the requested amount of the underlying tokens to address(this). /// @param amount The requested amount we want to withdraw. function _withdraw(uint256 amount) internal virtual; /// @notice Withdraw the maximum available amount of the invested assets to address(this). /// @dev This shouldn't revert (use try catch). function _exit() internal virtual; /// @notice Claim any rewards reward tokens and optionally sell them for the underlying token. /// @dev Doesn't need to be implemented if we don't expect any rewards. function _harvestRewards() internal virtual {} //** End strategy implementation */ modifier isActive() { require(!exited, "BentoBox Strategy: exited"); _; } modifier onlyBentoBox() { require(msg.sender == bentoBox, "BentoBox Strategy: only BentoBox"); _; } modifier onlyExecutor() { require(strategyExecutors[msg.sender], "BentoBox Strategy: only Executors"); _; } function setStrategyExecutor(address executor, bool value) external onlyOwner { strategyExecutors[executor] = value; emit LogSetStrategyExecutor(executor, value); } /// @inheritdoc IStrategy function skim(uint256 amount) external override { _skim(amount); } /// @notice Harvest profits while preventing a sandwich attack exploit. /// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox. /// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation. /// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox. /// @param harvestRewards If we want to claim any accrued reward tokens /// @dev maxBalance can be set to 0 to keep the previous value. /// @dev maxChangeAmount can be set to 0 to allow for full rebalancing. function safeHarvest( uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards ) external onlyExecutor { if (harvestRewards) { _harvestRewards(); } if (maxBalance > 0) { maxBentoBoxBalance = maxBalance; } IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount); } /// @inheritdoc IStrategy function withdraw(uint256 amount) external override isActive onlyBentoBox returns (uint256 actualAmount) { _withdraw(amount); /// @dev Make sure we send and report the exact same amount of tokens by using balanceOf. actualAmount = IERC20(strategyToken).balanceOf(address(this)); IERC20(strategyToken).safeTransfer(bentoBox, actualAmount); } /// @inheritdoc IStrategy /// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { _exit(); /// @dev Check balance of token on the contract. uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this)); /// @dev Calculate tokens added (or lost). amountAdded = int256(actualBalance) - int256(balance); /// @dev Transfer all tokens to bentoBox. IERC20(strategyToken).safeTransfer(bentoBox, actualBalance); /// @dev Flag as exited, allowing the owner to manually deal with any amounts available later. exited = true; } /** @dev After exited, the owner can perform ANY call. This is to rescue any funds that didn't get released during exit or got earned afterwards due to vesting or airdrops, etc. */ function afterExit( address to, uint256 value, bytes memory data ) public onlyOwner returns (bool success) { require(exited, "BentoBox Strategy: not exited"); (success, ) = to.call{value: value}(data); } } contract USTStrategyV3 is BaseStrategy { using SafeERC20 for IERC20; IAnchorRouter public constant router = IAnchorRouter(0xcEF9E167d3f8806771e9bac1d4a0d568c39a9388); IExchangeRateFeeder public feeder = IExchangeRateFeeder(0x24a76073Ab9131b25693F3b75dD1ce996fd3116c); IERC20 public constant UST = IERC20(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD); IERC20 public constant aUST = IERC20(0xa8De3e3c934e2A1BB08B010104CcaBBD4D6293ab); address private constant degenBox = 0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce; uint256 public fee; // fees on ust address public feeCollector; constructor(address strategyExecutor, address _feeCollector) BaseStrategy(address(UST), degenBox, address(0), address(0), strategyExecutor) { UST.approve(address(router), type(uint256).max); aUST.approve(address(router), type(uint256).max); feeCollector = _feeCollector; fee = 10; } function _skim(uint256 amount) internal override { router.depositStable(amount); } /** @inheritdoc IStrategy @dev Only BentoBox can call harvest on this strategy. @dev Ensures that (1) the caller was this contract (called through the safeHarvest function) and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits. */ function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) { /** @dev Don't revert if conditions aren't met in order to allow BentoBox to continiue execution as it might need to do a rebalance. */ if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) { int256 amount = _harvest(balance); /** @dev Since harvesting of rewards is accounted for seperately we might also have some underlying tokens in the contract that the _harvest call doesn't report. E.g. reward tokens that have been sold into the underlying tokens which are now sitting in the contract. Meaning the amount returned by the internal _harvest function isn't necessary the final profit/loss amount */ uint256 contractBalance = IERC20(strategyToken).balanceOf(address(this)); if (amount >= 0) { // _harvest reported a profit if (contractBalance >= uint256(amount)) { uint256 feeAmount = (uint256(amount) * fee) / 100; uint256 toTransfer = uint256(amount) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, uint256(toTransfer)); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (int256(toTransfer)); } else { uint256 feeAmount = (uint256(contractBalance) * fee) / 100; uint256 toTransfer = uint256(contractBalance) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, toTransfer); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (int256(toTransfer)); } } else { // we made a loss return amount; } } return int256(0); } function _harvest(uint256 balance) internal view override returns (int256) { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 keep = toAUST(balance, exchangeRate); uint256 total = aUST.balanceOf(address(this)) + toAUST(UST.balanceOf(address(this)), exchangeRate); return int256(toUST(total, exchangeRate)) - int256(toUST(keep, exchangeRate)); } function _withdraw(uint256 amount) internal override {} function redeemEarnings() external onlyExecutor { uint256 balanceToKeep = IBentoBoxMinimal(bentoBox).strategyData(address(UST)).balance; uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 liquid = UST.balanceOf(address(this)); uint256 total = toUST(aUST.balanceOf(address(this)), exchangeRate) + liquid; if (total > balanceToKeep) { router.redeemStable(toAUST(total - balanceToKeep - liquid, exchangeRate)); } } function safeDeposit(uint256 amount) external onlyExecutor { _skim(amount); } function safeWithdraw(uint256 amount) external onlyExecutor { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 requested = toAUST(amount, exchangeRate); router.redeemStable(requested); } function safeWithdrawFromAUST(uint256 amount) external onlyExecutor { router.redeemStable(amount); } function updateExchangeRateFeeder(IExchangeRateFeeder feeder_) external onlyOwner { feeder = feeder_; } function setFeeCollector(address _feeCollector, uint256 _fee) external onlyOwner { require(_fee <= 100, "max fee is 100"); feeCollector = _feeCollector; fee = _fee; } function _exit() internal override { try router.redeemStable(aUST.balanceOf(address(this))) {} catch {} } function toUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * exchangeRate) / 1e18; } function toAUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * 1e18) / exchangeRate; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IStrategy { /// @notice Send the assets to the Strategy and call skim to invest them. /// @param amount The amount of tokens to invest. function skim(uint256 amount) external; /// @notice Harvest any profits made converted to the asset and pass them to the caller. /// @param balance The amount of tokens the caller thinks it has invested. /// @param sender The address of the initiator of this transaction. Can be used for reimbursements, etc. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function harvest(uint256 balance, address sender) external returns (int256 amountAdded); /// @notice Withdraw assets. The returned amount can differ from the requested amount due to rounding. /// @dev The `actualAmount` should be very close to the amount. /// The difference should NOT be used to report a loss. That's what harvest is for. /// @param amount The requested amount the caller wants to withdraw. /// @return actualAmount The real amount that is withdrawn. function withdraw(uint256 amount) external returns (uint256 actualAmount); /// @notice Withdraw all assets in the safest way possible. This shouldn't fail. /// @param balance The amount of tokens the caller thinks it has invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function exit(uint256 balance) external returns (int256 amountAdded); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IUniswapV2Pair { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; /// @notice Minimal interface for BentoBox token vault interactions - `token` is aliased as `address` from `IERC20` for code simplicity. interface IBentoBoxMinimal { struct Rebase { uint128 elastic; uint128 base; } struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that BentoBox thinks is in there } function strategyData(address token) external view returns (StrategyData memory); /// @notice Balance per ERC-20 token per account in shares. function balanceOf(address, address) external view returns (uint256); /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( address token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( address token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. function transfer( address token, address from, address to, uint256 share ) external; /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( address token, uint256 amount, bool roundUp ) external view returns (uint256 share); /// @dev Helper function to represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( address token, uint256 share, bool roundUp ) external view returns (uint256 amount); /// @notice Registers this contract so that users can approve it for the BentoBox. function registerProtocol() external; function totals(address token) external view returns (Rebase memory); function harvest( address token, bool balance, uint256 maxChangeAmount ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; import "../interfaces/IUniswapV2Pair.sol"; /* The following library is modified from @sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol changes: - remove SafeMathUniswap library and replace all usage of it with basic operations - change casting from uint to bytes20 in pair address calculation and shift by 96 bits before casting */ library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order 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, bytes32 pairCodeHash ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); // Since Solidity 0.8.0 explicit conversions from literals larger than type(uint160).max to address are disallowed. // https://docs.soliditylang.org/en/develop/080-breaking-changes.html#new-restrictions pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); } } } }
* @dev Don't revert if conditions aren't met in order to allow* @dev Since harvesting of rewards is accounted for seperately we might also have _harvest reported a profit
@dev Ensures that (1) the caller was this contract (called through the safeHarvest function) and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits. */ function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) { BentoBox to continiue execution as it might need to do a rebalance. */ if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) { int256 amount = _harvest(balance); some underlying tokens in the contract that the _harvest call doesn't report. E.g. reward tokens that have been sold into the underlying tokens which are now sitting in the contract. Meaning the amount returned by the internal _harvest function isn't necessary the final profit/loss amount */ uint256 contractBalance = IERC20(strategyToken).balanceOf(address(this)); if (amount >= 0) { if (contractBalance >= uint256(amount)) { uint256 feeAmount = (uint256(amount) * fee) / 100; uint256 toTransfer = uint256(amount) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, uint256(toTransfer)); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (int256(toTransfer)); uint256 feeAmount = (uint256(contractBalance) * fee) / 100; uint256 toTransfer = uint256(contractBalance) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, toTransfer); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (int256(toTransfer)); } } } return int256(0); }
11,820,091
[ 1, 22293, 1404, 15226, 309, 4636, 11526, 1404, 5100, 316, 1353, 358, 1699, 225, 7897, 17895, 90, 10100, 434, 283, 6397, 353, 2236, 329, 364, 22282, 5173, 732, 4825, 2546, 1240, 389, 30250, 26923, 14010, 279, 450, 7216, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 632, 5206, 1374, 8421, 716, 261, 21, 13, 326, 4894, 1703, 333, 6835, 261, 11777, 3059, 326, 4183, 44, 297, 26923, 445, 13, 203, 3639, 471, 261, 22, 13, 716, 732, 854, 486, 3832, 284, 1949, 313, 318, 635, 279, 7876, 605, 29565, 3514, 443, 1724, 1347, 17895, 90, 10100, 9214, 1282, 18, 1195, 203, 565, 445, 17895, 26923, 12, 11890, 5034, 11013, 16, 1758, 5793, 13, 3903, 3849, 15083, 1338, 38, 29565, 3514, 1135, 261, 474, 5034, 13, 288, 203, 5411, 605, 29565, 3514, 358, 466, 8767, 344, 4588, 487, 518, 4825, 1608, 358, 741, 279, 283, 12296, 18, 1195, 203, 203, 3639, 309, 261, 15330, 422, 1758, 12, 2211, 13, 597, 23450, 29565, 3514, 2930, 2840, 12, 70, 29565, 3514, 2934, 3307, 1031, 12, 14914, 1345, 2934, 22318, 1648, 943, 38, 29565, 3514, 13937, 597, 11013, 405, 374, 13, 288, 203, 5411, 509, 5034, 3844, 273, 389, 30250, 26923, 12, 12296, 1769, 203, 203, 5411, 2690, 6808, 2430, 316, 326, 6835, 716, 326, 389, 30250, 26923, 745, 3302, 1404, 2605, 18, 7010, 5411, 512, 18, 75, 18, 19890, 2430, 716, 1240, 2118, 272, 1673, 1368, 326, 6808, 2430, 1492, 854, 2037, 10982, 1787, 316, 326, 6835, 18, 203, 5411, 21979, 310, 326, 3844, 2106, 635, 326, 2713, 389, 30250, 26923, 445, 5177, 1404, 4573, 326, 727, 450, 7216, 19, 7873, 3844, 1195, 203, 5411, 2254, 5034, 6835, 13937, 273, 467, 654, 39, 3462, 12, 14914, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 5411, 309, 261, 8949, 1545, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.9; library StringUtils { /// @dev Does a byte-by-byte lexicographical comparison of two strings. /// @return a negative number if `_a` is smaller, zero if they are equal /// and a positive number if `_b` is smaller. function compare(string memory _a, string memory _b) pure internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); if (a.length < b.length) return -1; if (a.length > b.length) return 1; for (uint i = 0; i < a.length; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; return 0; } /// @dev Compares two strings and returns true iff they are equal. function equal(string memory _a, string memory _b) pure internal returns (bool) { return compare(_a, _b) == 0; } }
@dev Does a byte-by-byte lexicographical comparison of two strings. @return a negative number if `_a` is smaller, zero if they are equal and a positive number if `_b` is smaller.
function compare(string memory _a, string memory _b) pure internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); if (a.length < b.length) return -1; if (a.length > b.length) return 1; for (uint i = 0; i < a.length; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; return 0; }
12,659,613
[ 1, 10154, 279, 1160, 17, 1637, 17, 7229, 30089, 8829, 1706, 5826, 434, 2795, 2064, 18, 327, 279, 6092, 1300, 309, 1375, 67, 69, 68, 353, 10648, 16, 3634, 309, 2898, 854, 3959, 471, 279, 6895, 1300, 309, 1375, 67, 70, 68, 353, 10648, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3400, 12, 1080, 3778, 389, 69, 16, 533, 3778, 389, 70, 13, 16618, 2713, 1135, 261, 474, 13, 288, 203, 3639, 1731, 3778, 279, 273, 1731, 24899, 69, 1769, 203, 3639, 1731, 3778, 324, 273, 1731, 24899, 70, 1769, 203, 3639, 309, 261, 69, 18, 2469, 411, 324, 18, 2469, 13, 203, 5411, 327, 300, 21, 31, 203, 3639, 309, 261, 69, 18, 2469, 405, 324, 18, 2469, 13, 203, 5411, 327, 404, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 279, 18, 2469, 31, 277, 965, 13, 203, 5411, 309, 261, 69, 63, 77, 65, 411, 324, 63, 77, 5717, 203, 7734, 327, 300, 21, 31, 203, 5411, 469, 309, 261, 69, 63, 77, 65, 405, 324, 63, 77, 5717, 203, 7734, 327, 404, 31, 203, 3639, 327, 374, 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 ]
pragma solidity 0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract MinerOneToken is MintableToken { using SafeMath for uint256; string public name = "MinerOne"; string public symbol = "MIO"; uint8 public decimals = 18; /** * This struct holds data about token holder dividends */ struct Account { /** * Last amount of dividends seen at the token holder payout */ uint256 lastDividends; /** * Amount of wei contract needs to pay to token holder */ uint256 fixedBalance; /** * Unpayed wei amount due to rounding */ uint256 remainder; } /** * Mapping which holds all token holders data */ mapping(address => Account) internal accounts; /** * Running total of all dividends distributed */ uint256 internal totalDividends; /** * Holds an amount of unpayed weis */ uint256 internal reserved; /** * Raised when payment distribution occurs */ event Distributed(uint256 amount); /** * Raised when shareholder withdraws his profit */ event Paid(address indexed to, uint256 amount); /** * Raised when the contract receives Ether */ event FundsReceived(address indexed from, uint256 amount); modifier fixBalance(address _owner) { Account storage account = accounts[_owner]; uint256 diff = totalDividends.sub(account.lastDividends); if (diff > 0) { uint256 numerator = account.remainder.add(balances[_owner].mul(diff)); account.fixedBalance = account.fixedBalance.add(numerator.div(totalSupply_)); account.remainder = numerator % totalSupply_; account.lastDividends = totalDividends; } _; } modifier onlyWhenMintingFinished() { require(mintingFinished); _; } function () external payable { withdraw(msg.sender, msg.value); } function deposit() external payable { require(msg.value > 0); require(msg.value <= this.balance.sub(reserved)); totalDividends = totalDividends.add(msg.value); reserved = reserved.add(msg.value); Distributed(msg.value); } /** * Returns unpayed wei for a given address */ function getDividends(address _owner) public view returns (uint256) { Account storage account = accounts[_owner]; uint256 diff = totalDividends.sub(account.lastDividends); if (diff > 0) { uint256 numerator = account.remainder.add(balances[_owner].mul(diff)); return account.fixedBalance.add(numerator.div(totalSupply_)); } else { return 0; } } function transfer(address _to, uint256 _value) public onlyWhenMintingFinished fixBalance(msg.sender) fixBalance(_to) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public onlyWhenMintingFinished fixBalance(_from) fixBalance(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } function payoutToAddress(address[] _holders) external { require(_holders.length > 0); require(_holders.length <= 100); for (uint256 i = 0; i < _holders.length; i++) { withdraw(_holders[i], 0); } } /** * Token holder must call this to receive dividends */ function withdraw(address _benefeciary, uint256 _toReturn) internal onlyWhenMintingFinished fixBalance(_benefeciary) returns (bool) { uint256 amount = accounts[_benefeciary].fixedBalance; reserved = reserved.sub(amount); accounts[_benefeciary].fixedBalance = 0; uint256 toTransfer = amount.add(_toReturn); if (toTransfer > 0) { _benefeciary.transfer(toTransfer); } if (amount > 0) { Paid(_benefeciary, amount); } return true; } } contract MinerOneCrowdsale is Ownable { using SafeMath for uint256; // Wallet where all ether will be address public constant WALLET = 0x2C2b3885BC8B82Ad4D603D95ED8528Ef112fE8F2; // Wallet for team tokens address public constant TEAM_WALLET = 0x997faEf570B534E5fADc8D2D373e2F11aF4e115a; // Wallet for research and development tokens address public constant RESEARCH_AND_DEVELOPMENT_WALLET = 0x770998331D6775c345B1807c40413861fc4D6421; // Wallet for bounty tokens address public constant BOUNTY_WALLET = 0xd481Aab166B104B1aB12e372Ef7af6F986f4CF19; uint256 public constant UINT256_MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint256 public constant ICO_TOKENS = 287000000e18; uint8 public constant ICO_TOKENS_PERCENT = 82; uint8 public constant TEAM_TOKENS_PERCENT = 10; uint8 public constant RESEARCH_AND_DEVELOPMENT_TOKENS_PERCENT = 6; uint8 public constant BOUNTY_TOKENS_PERCENT = 2; uint256 public constant SOFT_CAP = 3000000e18; uint256 public constant START_TIME = 1518692400; // 2018/02/15 11:00 UTC +0 uint256 public constant RATE = 1000; // 1000 tokens costs 1 ether uint256 public constant LARGE_PURCHASE = 10000e18; uint256 public constant LARGE_PURCHASE_BONUS = 4; uint256 public constant TOKEN_DESK_BONUS = 3; uint256 public constant MIN_TOKEN_AMOUNT = 100e18; Phase[] internal phases; struct Phase { uint256 till; uint8 discount; } // The token being sold MinerOneToken public token; // amount of raised money in wei uint256 public weiRaised; // refund vault used to hold funds while crowdsale is running RefundVault public vault; uint256 public currentPhase = 0; bool public isFinalized = false; address private tokenMinter; address private tokenDeskProxy; uint256 public icoEndTime = 1526558400; // 2018/05/17 12:00 UTC +0 /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); /** * When there no tokens left to mint and token minter tries to manually mint tokens * this event is raised to signal how many tokens we have to charge back to purchaser */ event ManualTokenMintRequiresRefund(address indexed purchaser, uint256 value); function MinerOneCrowdsale(address _token) public { phases.push(Phase({ till: 1519214400, discount: 35 })); // 2018/02/21 12:00 UTC +0 phases.push(Phase({ till: 1519905600, discount: 30 })); // 2018/03/01 12:00 UTC +0 phases.push(Phase({ till: 1521201600, discount: 25 })); // 2018/03/16 12:00 UTC +0 phases.push(Phase({ till: 1522584000, discount: 20 })); // 2018/04/01 12:00 UTC +0 phases.push(Phase({ till: 1524312000, discount: 15 })); // 2018/04/21 12:00 UTC +0 phases.push(Phase({ till: 1525608000, discount: 10 })); // 2018/05/06 12:00 UTC +0 phases.push(Phase({ till: 1526472000, discount: 5 })); // 2018/05/16 12:00 UTC +0 phases.push(Phase({ till: UINT256_MAX, discount:0 })); // unlimited token = MinerOneToken(_token); vault = new RefundVault(WALLET); tokenMinter = msg.sender; } modifier onlyTokenMinterOrOwner() { require(msg.sender == tokenMinter || msg.sender == owner); _; } // fallback function can be used to buy tokens or claim refund function () external payable { if (!isFinalized) { buyTokens(msg.sender, msg.sender); } else { claimRefund(); } } function mintTokens(address[] _receivers, uint256[] _amounts) external onlyTokenMinterOrOwner { require(_receivers.length > 0 && _receivers.length <= 100); require(_receivers.length == _amounts.length); require(!isFinalized); for (uint256 i = 0; i < _receivers.length; i++) { address receiver = _receivers[i]; uint256 amount = _amounts[i]; require(receiver != address(0)); require(amount > 0); uint256 excess = appendContribution(receiver, amount); if (excess > 0) { ManualTokenMintRequiresRefund(receiver, excess); } } } // low level token purchase function function buyTokens(address sender, address beneficiary) public payable { require(beneficiary != address(0)); require(sender != address(0)); require(validPurchase()); uint256 weiReceived = msg.value; uint256 nowTime = getNow(); // this loop moves phases and insures correct stage according to date while (currentPhase < phases.length && phases[currentPhase].till < nowTime) { currentPhase = currentPhase.add(1); } // calculate token amount to be created uint256 tokens = calculateTokens(weiReceived); if (tokens < MIN_TOKEN_AMOUNT) revert(); uint256 excess = appendContribution(beneficiary, tokens); uint256 refund = (excess > 0 ? excess.mul(weiReceived).div(tokens) : 0); weiReceived = weiReceived.sub(refund); weiRaised = weiRaised.add(weiReceived); if (refund > 0) { sender.transfer(refund); } TokenPurchase(sender, beneficiary, weiReceived, tokens.sub(excess)); if (goalReached()) { WALLET.transfer(weiReceived); } else { vault.deposit.value(weiReceived)(sender); } } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasEnded()); if (goalReached()) { vault.close(); uint256 totalSupply = token.totalSupply(); uint256 teamTokens = uint256(TEAM_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT); token.mint(TEAM_WALLET, teamTokens); uint256 rdTokens = uint256(RESEARCH_AND_DEVELOPMENT_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT); token.mint(RESEARCH_AND_DEVELOPMENT_WALLET, rdTokens); uint256 bountyTokens = uint256(BOUNTY_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT); token.mint(BOUNTY_WALLET, bountyTokens); token.finishMinting(); token.transferOwnership(token); } else { vault.enableRefunds(); } Finalized(); isFinalized = true; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return getNow() > icoEndTime || token.totalSupply() == ICO_TOKENS; } function goalReached() public view returns (bool) { return token.totalSupply() >= SOFT_CAP; } function setTokenMinter(address _tokenMinter) public onlyOwner { require(_tokenMinter != address(0)); tokenMinter = _tokenMinter; } function setTokenDeskProxy(address _tokekDeskProxy) public onlyOwner { require(_tokekDeskProxy != address(0)); tokenDeskProxy = _tokekDeskProxy; } function setIcoEndTime(uint256 _endTime) public onlyOwner { require(_endTime > icoEndTime); icoEndTime = _endTime; } function getNow() internal view returns (uint256) { return now; } function calculateTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 tokens = _weiAmount.mul(RATE).mul(100).div(uint256(100).sub(phases[currentPhase].discount)); uint256 bonus = 0; if (currentPhase > 0) { bonus = bonus.add(tokens >= LARGE_PURCHASE ? LARGE_PURCHASE_BONUS : 0); bonus = bonus.add(msg.sender == tokenDeskProxy ? TOKEN_DESK_BONUS : 0); } return tokens.add(tokens.mul(bonus).div(100)); } function appendContribution(address _beneficiary, uint256 _tokens) internal returns (uint256) { uint256 excess = 0; uint256 tokensToMint = 0; uint256 totalSupply = token.totalSupply(); if (totalSupply.add(_tokens) < ICO_TOKENS) { tokensToMint = _tokens; } else { tokensToMint = ICO_TOKENS.sub(totalSupply); excess = _tokens.sub(tokensToMint); } if (tokensToMint > 0) { token.mint(_beneficiary, tokensToMint); } return excess; } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = getNow() >= START_TIME && getNow() <= icoEndTime; bool nonZeroPurchase = msg.value != 0; bool canMint = token.totalSupply() < ICO_TOKENS; bool validPhase = (currentPhase < phases.length); return withinPeriod && nonZeroPurchase && canMint && validPhase; } }
low level token purchase function this loop moves phases and insures correct stage according to date
function buyTokens(address sender, address beneficiary) public payable { require(beneficiary != address(0)); require(sender != address(0)); require(validPurchase()); uint256 weiReceived = msg.value; uint256 nowTime = getNow(); while (currentPhase < phases.length && phases[currentPhase].till < nowTime) { currentPhase = currentPhase.add(1); } if (tokens < MIN_TOKEN_AMOUNT) revert(); uint256 excess = appendContribution(beneficiary, tokens); uint256 refund = (excess > 0 ? excess.mul(weiReceived).div(tokens) : 0); weiReceived = weiReceived.sub(refund); weiRaised = weiRaised.add(weiReceived); if (refund > 0) { sender.transfer(refund); } TokenPurchase(sender, beneficiary, weiReceived, tokens.sub(excess)); if (goalReached()) { WALLET.transfer(weiReceived); vault.deposit.value(weiReceived)(sender); } }
12,987,455
[ 1, 821, 1801, 1147, 23701, 445, 333, 2798, 13934, 24642, 471, 2763, 1823, 3434, 6009, 4888, 358, 1509, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 5157, 12, 2867, 5793, 16, 1758, 27641, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 877, 23164, 10663, 203, 203, 3639, 2254, 5034, 732, 77, 8872, 273, 1234, 18, 1132, 31, 203, 3639, 2254, 5034, 2037, 950, 273, 336, 8674, 5621, 203, 3639, 1323, 261, 2972, 11406, 411, 24642, 18, 2469, 597, 24642, 63, 2972, 11406, 8009, 88, 737, 411, 2037, 950, 13, 288, 203, 5411, 783, 11406, 273, 783, 11406, 18, 1289, 12, 21, 1769, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 7860, 411, 6989, 67, 8412, 67, 2192, 51, 5321, 13, 15226, 5621, 203, 203, 3639, 2254, 5034, 23183, 273, 714, 442, 4027, 12, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 3639, 2254, 5034, 16255, 273, 261, 338, 614, 405, 374, 692, 23183, 18, 16411, 12, 1814, 77, 8872, 2934, 2892, 12, 7860, 13, 294, 374, 1769, 203, 203, 3639, 732, 77, 8872, 273, 732, 77, 8872, 18, 1717, 12, 1734, 1074, 1769, 203, 3639, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 8872, 1769, 203, 203, 3639, 309, 261, 1734, 1074, 405, 374, 13, 288, 203, 5411, 5793, 18, 13866, 12, 1734, 1074, 1769, 203, 3639, 289, 203, 203, 3639, 3155, 23164, 12, 15330, 16, 27641, 74, 14463, 814, 16, 732, 77, 8872, 16, 2430, 18, 1717, 12, 338, 614, 2 ]
./full_match/4/0x0FEc9C9348E1AbC42cDb096EbDCc6F5358c47719/sources/tests/DeAuth/DAUTH.sol
Subtract from the sender
Balances[msg.sender] -= _value;
751,775
[ 1, 27904, 628, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 605, 26488, 63, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 8227, 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/1/0xf92474812721bF1cFD311505Ba16796F1C2c472b/sources/DMEX_Custody.sol
The DMEX Custody Contract Deposit ETH to contract
contract DMEX_Custody { address public DMEX_XDAI_CONTRACT; address public WETH9_ADDRESS; uint256 public destroyBlock; uint256 public ambInstructionGas = 2000000; function deposit() public payable { if (destroyed) revert("Contract destroyed"); } WETH9(WETH9_ADDRESS).deposit{value: msg.value}; function depositToken(address token, uint256 amount) public { require(!destroyed, "Contract destroyed"); sendDepositInstructionToAMBBridge(msg.sender, token, amount); } function depositTokenForUser(address token, uint256 amount, address user) public { require(!destroyed, "Contract destroyed"); sendDepositInstructionToAMBBridge(user, token, amount); } function sendDepositInstructionToAMBBridge(address user, address token, uint256 amount) internal { Token(token).approve(AMBMediatorContract, amount); bytes memory data = abi.encode(user); uint256 gas = ambInstructionGas; GnosisMediator(AMBMediatorContract).relayTokensAndCall(token, DMEX_XDAI_CONTRACT, amount, data); } function withdrawForUser( ) public onlyAMBBridge returns (bool success) { } } else { }
3,981,376
[ 1, 1986, 463, 958, 60, 385, 641, 973, 13456, 4019, 538, 305, 512, 2455, 358, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 463, 958, 60, 67, 39, 641, 973, 288, 203, 565, 1758, 1071, 463, 958, 60, 67, 60, 9793, 45, 67, 6067, 2849, 1268, 31, 203, 565, 1758, 1071, 678, 1584, 44, 29, 67, 15140, 31, 203, 203, 203, 565, 2254, 5034, 1071, 5546, 1768, 31, 203, 203, 565, 2254, 5034, 1071, 13232, 11983, 27998, 273, 576, 9449, 31, 203, 203, 203, 377, 203, 203, 565, 445, 443, 1724, 1435, 1071, 8843, 429, 288, 203, 3639, 309, 261, 11662, 329, 13, 15226, 2932, 8924, 17689, 8863, 203, 203, 565, 289, 203, 203, 3639, 678, 1584, 44, 29, 12, 59, 1584, 44, 29, 67, 15140, 2934, 323, 1724, 95, 1132, 30, 1234, 18, 1132, 20451, 203, 565, 445, 443, 1724, 1345, 12, 2867, 1147, 16, 2254, 5034, 3844, 13, 1071, 288, 203, 3639, 2583, 12, 5, 11662, 329, 16, 315, 8924, 17689, 8863, 203, 203, 3639, 1366, 758, 1724, 11983, 774, 2192, 9676, 5404, 12, 3576, 18, 15330, 16, 1147, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 1345, 19894, 12, 2867, 1147, 16, 2254, 5034, 3844, 16, 1758, 729, 13, 1071, 288, 377, 203, 3639, 2583, 12, 5, 11662, 329, 16, 315, 8924, 17689, 8863, 377, 203, 203, 4202, 203, 3639, 1366, 758, 1724, 11983, 774, 2192, 9676, 5404, 12, 1355, 16, 1147, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 1366, 758, 1724, 11983, 774, 2192, 9676, 5404, 12, 2867, 729, 16, 1758, 1147, 16, 2254, 5034, 3844, 13, 2713, 203, 565, 288, 203, 203, 3639, 3155, 2 ]
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.10; import "Strings.sol"; import "MerkleProof.sol"; import "ERC721Enum.sol"; import "Grace.sol"; import "IAngelz.sol"; import "ISanctuary.sol"; contract Angelz is IAngelz, ERC721Enum { using Strings for uint256; // mint price uint256 public constant MINT_PRICE = .0543 ether; // max number of tokens that can be minted - 30,616 uint256 public immutable MAX_TOKENS; // number of tokens pay with eth - 25% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; string public baseURI; bytes32 private rootWL; string internal constant baseExtension = ".json"; bool public pauseMint = true; bool public pausePreMint = true; address public immutable owner; uint256 public freeMint = 500; address private constant addressOne = 0xD70Ee431F074Fb835132ddE35255F8274A51D90b; address private constant addressTwo = 0x13542174BA72e443450926Ea7fC15ED6D66491e0; address private constant addressThree = 0xcC187E04A67c5601693dB7F25E4309D066512a24; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => AngelHuman) public tokenTraits; // reference to the Sanctuary for choosing random Angel thieves ISanctuary public sanctuary; // reference to $GRACE for burning on mint GRACE public grace; /** * instantiates contract and rarity tables */ constructor(address _grace, string memory _initBaseURI) ERC721P("AngelzGame", "AG") { owner = msg.sender; grace = GRACE(_grace); setBaseURI(_initBaseURI); MAX_TOKENS = 30616; PAID_TOKENS = MAX_TOKENS / 4; } modifier mintOpen() { require(!pauseMint, "PauseMint"); _; } modifier preMintOpen() { require(!pausePreMint, "PausePreMint"); _; } modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "onlyOwner"); } /** EXTERNAL */ /** * mint a token - 90% Human, 10% Angel * The first 25% are 0.0543 eth, the remaining cost $GRACE */ function mint(uint256 amount, bool stake) external payable mintOpen { require(tx.origin == msg.sender, "Only EOA"); require(minted + amount <= MAX_TOKENS, "Allminted"); require(amount > 0 && amount <= 10, "nomorethan10"); if (minted < PAID_TOKENS) { if (minted < freeMint) { require(amount <= 2, "freelimit2pertx"); require(msg.value == 0, "bruh its free"); } else { require(minted + amount <= PAID_TOKENS, "Allonsaleminted"); require(msg.value >= amount * MINT_PRICE, "notenougheth"); } } else { require(msg.value == 0, "payinGRACE"); } uint256 totalGraceTokenCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint256 i = 0; i < amount; i++) { seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(sanctuary), minted); tokenIds[i] = minted; } minted++; totalGraceTokenCost += mintCost(minted); } if (totalGraceTokenCost > 0) grace.burn(_msgSender(), totalGraceTokenCost); if (stake) sanctuary.addManyToSanctuaryAndHeaven(_msgSender(), tokenIds); } function preMint( uint256 amount, bool stake, bytes32[] calldata proof, uint256 _number ) external payable preMintOpen { require(tx.origin == msg.sender, "Only EOA"); uint16 eligibilitySender = isEligible(proof, _number); if (eligibilitySender == 0) { revert("notWL"); } require(minted + amount <= PAID_TOKENS, "Allminted"); require(amount > 0 && amount <= 10, "nomorethan10"); if (minted < freeMint) { require(amount <= 2, "freelimit2pertx"); require(msg.value == 0, "bruh its free"); } else { require(msg.value >= amount * MINT_PRICE, "notenougheth"); } uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint256 i = 0; i < amount; i++) { seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(sanctuary), minted); tokenIds[i] = minted; } minted++; } if (stake) sanctuary.addManyToSanctuaryAndHeaven(_msgSender(), tokenIds); } /** * the first 25% are 0.0543 ETH * the next 25% are 10000 $GRACE * the next 25% are 20000 $GRACE * the final 25% are 40000 $GRACE * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= (MAX_TOKENS * 2) / 4) return 10000 ether; if (tokenId <= (MAX_TOKENS * 3) / 4) return 20000 ether; return 40000 ether; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode the Sanctuary's approval so that users don't have to waste gas approving if (_msgSender() != address(sanctuary)) require( _isApprovedOrOwner(_msgSender(), tokenId), "Not owner nor approved" ); _transfer(from, to, tokenId); } /** INTERNAL */ function _baseURI() internal view virtual returns (string memory) { return baseURI; } /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (AngelHuman memory t) { t = selectTraits(seed); tokenTraits[tokenId] = t; return t; } function selectTraits(uint256 seed) internal view returns (AngelHuman memory t) { t.human = (seed & 0xFFFF) % 10 != 0; seed >>= 16; if (t.human) { t.angelicIndex = 0; return t; } uint16 randomAngelicValue = uint16(seed & 0xFFFF) % 10; if (randomAngelicValue == 0) { t.angelicIndex = 8; } else if (randomAngelicValue == 1 || randomAngelicValue == 2) { t.angelicIndex = 7; } else if ( randomAngelicValue == 3 || randomAngelicValue == 4 || randomAngelicValue == 5 ) { t.angelicIndex = 6; } else { t.angelicIndex = 5; } } /** * the first 25% (ETH purchases) go to the minter * the remaining 75% have a 10% chance to be given to a random staked angel * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Angel thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = sanctuary.randomAngelOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ) ) ); } /** READ */ function isEligible(bytes32[] calldata proof, uint256 _number) public view returns (uint16 eligibility) { bytes32 leaf = keccak256(abi.encodePacked(_number, msg.sender)); if (MerkleProof.verify(proof, rootWL, leaf)) return 1; return 0; } function getTokenTraits(uint256 tokenId) external view override returns (AngelHuman memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** ADMIN */ /** * called after deployment so that the contract can get random angel thieves * @param _sanctuary the address of the Sanctuary */ function setSanctuary(address _sanctuary) external onlyOwner { sanctuary = ISanctuary(_sanctuary); } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setRoot(bytes32 _rootWL) external onlyOwner { rootWL = _rootWL; } /** * allows owner to withdraw funds from minting */ function withdrawAll() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No money"); _withdraw(addressOne, (balance * 30) / 100); _withdraw(addressTwo, (balance * 30) / 100); _withdraw(addressThree, (balance * 30) / 100); _withdraw(msg.sender, address(this).balance); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{ value: _amount }(""); require(success, "Transfer failed"); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } function setNumFreeMint(uint256 _freeMint) external onlyOwner { freeMint = _freeMint; } function setPauseMint(bool _setPauseMint) external onlyOwner { if (_setPauseMint) { pauseMint = true; } else { pauseMint = false; } } function setPausePreMint(bool _setPausePreMint) external onlyOwner { if (_setPausePreMint) { pausePreMint = true; } else { pausePreMint = false; } } /** RENDER */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "DNE"); string memory currentBaseURI = _baseURI(); return ( bytes(currentBaseURI).length > 0 ? string( abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension) ) : "" ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.10; import "ERC721P.sol"; import "IERC721Enumerable.sol"; abstract contract ERC721Enum is ERC721P, IERC721Enumerable { function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721P) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256 tokenId) { require(index < ERC721P.balanceOf(owner), "ERC721Enum: owner ioob"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) { if (count == index) return i; else ++count; } } require(false, "ERC721Enum: owner ioob"); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { require(0 < ERC721P.balanceOf(owner), "ERC721Enum: owner ioob"); uint256 tokenCount = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); } return tokenIds; } function totalSupply() public view virtual override returns (uint256) { return _owners.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enum.totalSupply(), "ERC721Enum: global ioob"); return index; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.10; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "ERC165.sol"; abstract contract ERC721P is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); uint256 count = 0; uint256 length = _owners.length; for (uint256 i = 0; i < length; ++i) { if (owner == _owners[i]) { ++count; } } delete length; return count; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721P.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 getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } 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 { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _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 { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } 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" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721P.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721P.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721P.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); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721P.ownerOf(tokenId), to, tokenId); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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 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 LICENSE pragma solidity ^0.8.10; import "ERC20.sol"; import "Ownable.sol"; contract GRACE is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; constructor() ERC20("$GRACE", "GRACE") {} /** * mints $GRACE to a recipient * @param to the recipient of the $GRACE * @param amount the amount of $GRACE to mint */ function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } /** * burns $GRACE from a holder * @param from the holder of the $GRACE * @param amount the amount of $GRACE to burn */ function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "IERC20.sol"; import "IERC20Metadata.sol"; import "Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.10; interface IAngelz { // struct to store each token's traits struct AngelHuman { bool human; uint8 angelicIndex; } function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (AngelHuman memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.10; interface ISanctuary { function addManyToSanctuaryAndHeaven( address account, uint16[] calldata tokenIds ) external; function randomAngelOwner(uint256 seed) external view returns (address); }
* generates a pseudorandom number @param seed a value ensure different outcomes for different sources in the same block @return a pseudorandom value/
function random(uint256 seed) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ) ) ); }
1,294,720
[ 1, 3441, 815, 279, 29606, 280, 2111, 1300, 225, 5009, 279, 460, 3387, 3775, 29867, 364, 3775, 5550, 316, 326, 1967, 1203, 327, 279, 29606, 280, 2111, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 225, 445, 2744, 12, 11890, 5034, 5009, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 203, 1377, 2254, 5034, 12, 203, 3639, 417, 24410, 581, 5034, 12, 203, 1850, 24126, 18, 3015, 4420, 329, 12, 203, 5411, 2229, 18, 10012, 16, 203, 5411, 1203, 2816, 12, 2629, 18, 2696, 300, 404, 3631, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 5009, 203, 1850, 262, 203, 3639, 262, 203, 1377, 11272, 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 ]
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/SettleLayer.sol
@notice Settle the collateral exchange associated with a the initailization of a new pool in the exchange. @oaran recv The address that will be covering any debits associated with the initialization of the pool. @param base The ERC20 address of the base token collateral in the pair (if 0x0 indicates that the collateral is native Eth). @param baseFlow The amount of flow associated with the base side of the pair. By convention negative for credits paid to user, positive for debits, but will always be positive/debit for this operation. @param quote The ERC20 address of the quote token collateral in the pair. @param quoteFlow The flow associated with the quote side of the pair. /
function settleInitFlow (address recv, address base, int128 baseFlow, address quote, int128 quoteFlow) internal { (uint256 baseSnap, uint256 quoteSnap) = snapOpenBalance(base, quote); settleFlat(recv, recv, base, baseFlow, quote, quoteFlow, BOTH_RESERVE_FLAGS); assertCloseMatches(base, baseSnap, baseFlow); assertCloseMatches(quote, quoteSnap, quoteFlow); }
4,651,358
[ 1, 694, 5929, 326, 4508, 2045, 287, 7829, 3627, 598, 279, 326, 1208, 671, 1588, 434, 540, 279, 394, 2845, 316, 326, 7829, 18, 632, 83, 297, 304, 10665, 1021, 1758, 716, 903, 506, 5590, 310, 1281, 443, 6789, 3627, 598, 326, 2398, 10313, 434, 326, 2845, 18, 225, 1026, 1021, 4232, 39, 3462, 1758, 434, 326, 1026, 1147, 4508, 2045, 287, 316, 326, 3082, 261, 430, 374, 92, 20, 2398, 8527, 716, 326, 4508, 2045, 287, 353, 6448, 512, 451, 2934, 225, 1026, 5249, 1021, 3844, 434, 4693, 3627, 598, 326, 1026, 4889, 434, 326, 3082, 18, 1171, 2525, 15797, 6092, 364, 6197, 1282, 30591, 358, 729, 16, 6895, 364, 443, 6789, 16, 1171, 1496, 903, 3712, 506, 6895, 19, 323, 3682, 364, 333, 1674, 18, 225, 3862, 1021, 4232, 39, 3462, 1758, 434, 326, 3862, 1147, 4508, 2045, 287, 316, 326, 3082, 18, 225, 3862, 5249, 1021, 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, 444, 5929, 2570, 5249, 261, 2867, 10665, 16, 203, 11794, 1758, 1026, 16, 509, 10392, 1026, 5249, 16, 203, 11794, 1758, 3862, 16, 509, 10392, 3862, 5249, 13, 2713, 288, 203, 3639, 261, 11890, 5034, 1026, 24063, 16, 2254, 5034, 3862, 24063, 13, 273, 10915, 3678, 13937, 12, 1969, 16, 3862, 1769, 203, 3639, 444, 5929, 16384, 12, 18334, 16, 10665, 16, 1026, 16, 1026, 5249, 16, 3862, 16, 3862, 5249, 16, 29370, 67, 862, 2123, 3412, 67, 17836, 1769, 203, 3639, 1815, 4605, 6869, 12, 1969, 16, 1026, 24063, 16, 1026, 5249, 1769, 203, 3639, 1815, 4605, 6869, 12, 6889, 16, 3862, 24063, 16, 3862, 5249, 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 ]
./full_match/1/0x46d9F045F60B1613bd4eC0D0eE2b3B47Cb6501d9/sources/src/lib/proxy/ERC1967Proxy.sol
@dev The address of the current implementation
function _implementation() internal view virtual override returns (address) { return ERC1967Upgrade._getImplementation(); }
4,974,681
[ 1, 1986, 1758, 434, 326, 783, 4471, 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, 30810, 1435, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 327, 4232, 39, 3657, 9599, 10784, 6315, 588, 13621, 5621, 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 ]
//Address: 0x0d341E13F9f9bd6e02FA97e249A0a27522b0EFB1 //Contract name: SmartWallet //Balance: 0 Ether //Verification Date: 4/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string) {} function symbol() public constant returns (string) {} function decimals() public constant returns (uint8) {} function totalSupply() public constant returns (uint256) {} function balanceOf(address _owner) public constant returns (uint256) { _owner; } function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } ///@title - a contract that represents a smart wallet, created by Stox, for every new Stox user library SmartWalletLib { /* * Structs */ struct Wallet { address operatorAccount; address backupAccount; address userWithdrawalAccount; address feesAccount; } /* * Members */ string constant VERSION = "0.1"; /* * Modifiers */ modifier validAddress(address _address) { require(_address != 0x0); _; } modifier addressNotSet(address _address) { require(_address == 0); _; } modifier operatorOnly(address _operatorAccount) { require(msg.sender == _operatorAccount); _; } /* * Events */ event TransferToBackupAccount(address _token, address _backupAccount, uint _amount); event TransferToUserWithdrawalAccount(address _token, address _userWithdrawalAccount, uint _amount, address _feesToken, address _feesAccount, uint _fee); event SetUserWithdrawalAccount(address _userWithdrawalAccount); /* @dev Initialize the wallet with the operator and backupAccount address @param _self Wallet storage @param _backupAccount Operator account to release funds in case the user lost his withdrawal account @param _operator The operator account @param _feesAccount The account to transfer fees to */ function initWallet(Wallet storage _self, address _backupAccount, address _operator, address _feesAccount) public validAddress(_backupAccount) validAddress(_operator) validAddress(_feesAccount) { _self.operatorAccount = _operator; _self.backupAccount = _backupAccount; _self.feesAccount = _feesAccount; } /* @dev Setting the account of the user to send funds to. @param _self Wallet storage @param _userWithdrawalAccount The user account to withdraw funds to */ function setUserWithdrawalAccount(Wallet storage _self, address _userWithdrawalAccount) public operatorOnly(_self.operatorAccount) validAddress(_userWithdrawalAccount) addressNotSet(_self.userWithdrawalAccount) { _self.userWithdrawalAccount = _userWithdrawalAccount; SetUserWithdrawalAccount(_userWithdrawalAccount); } /* @dev Withdraw funds to a backup account. @param _self Wallet storage @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer */ function transferToBackupAccount(Wallet storage _self, IERC20Token _token, uint _amount) public operatorOnly(_self.operatorAccount) { _token.transfer(_self.backupAccount, _amount); TransferToBackupAccount(_token, _self.backupAccount, _amount); } /* @dev Withdraw funds to the user account. @param _self Wallet storage @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer @param _fee Fee to transfer */ function transferToUserWithdrawalAccount(Wallet storage _self, IERC20Token _token, uint _amount, IERC20Token _feesToken, uint _fee) public operatorOnly(_self.operatorAccount) validAddress(_self.userWithdrawalAccount) { if (_fee > 0) { _feesToken.transfer(_self.feesAccount, _fee); } _token.transfer(_self.userWithdrawalAccount, _amount); TransferToUserWithdrawalAccount(_token, _self.userWithdrawalAccount, _amount, _feesToken, _self.feesAccount, _fee); } } ///@title - a contract that represents a smart wallet, created by Stox, for every new Stox user contract SmartWallet { /* * Members */ using SmartWalletLib for SmartWalletLib.Wallet; SmartWalletLib.Wallet public wallet; // Wallet public wallet; /* * Events */ event TransferToBackupAccount(address _token, address _backupAccount, uint _amount); event TransferToUserWithdrawalAccount(address _token, address _userWithdrawalAccount, uint _amount, address _feesToken, address _feesAccount, uint _fee); event SetUserWithdrawalAccount(address _userWithdrawalAccount); /* @dev constructor @param _backupAccount A default operator's account to send funds to, in cases where the user account is unavailable or lost @param _operator The contract operator address @param _feesAccount The account to transfer fees to */ function SmartWallet(address _backupAccount, address _operator, address _feesAccount) public { wallet.initWallet(_backupAccount, _operator, _feesAccount); } /* @dev Setting the account of the user to send funds to. @param _userWithdrawalAccount The user account to withdraw funds to */ function setUserWithdrawalAccount(address _userWithdrawalAccount) public { wallet.setUserWithdrawalAccount(_userWithdrawalAccount); } /* @dev Withdraw funds to a backup account. @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer */ function transferToBackupAccount(IERC20Token _token, uint _amount) public { wallet.transferToBackupAccount(_token, _amount); } /* @dev Withdraw funds to the user account. @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer */ function transferToUserWithdrawalAccount(IERC20Token _token, uint _amount, IERC20Token _feesToken, uint _fee) public { wallet.transferToUserWithdrawalAccount(_token, _amount, _feesToken, _fee); } }
@title - a contract that represents a smart wallet, created by Stox, for every new Stox user Wallet public wallet;
contract SmartWallet { using SmartWalletLib for SmartWalletLib.Wallet; SmartWalletLib.Wallet public wallet; event TransferToBackupAccount(address _token, address _backupAccount, uint _amount); event TransferToUserWithdrawalAccount(address _token, address _userWithdrawalAccount, uint _amount, address _feesToken, address _feesAccount, uint _fee); event SetUserWithdrawalAccount(address _userWithdrawalAccount); @dev constructor @param _backupAccount A default operator's account to send funds to, in cases where the user account is unavailable or lost @param _operator The contract operator address @param _feesAccount The account to transfer fees to function SmartWallet(address _backupAccount, address _operator, address _feesAccount) public { wallet.initWallet(_backupAccount, _operator, _feesAccount); } @param _userWithdrawalAccount The user account to withdraw funds to @dev Setting the account of the user to send funds to. function setUserWithdrawalAccount(address _userWithdrawalAccount) public { wallet.setUserWithdrawalAccount(_userWithdrawalAccount); } @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer @dev Withdraw funds to a backup account. function transferToBackupAccount(IERC20Token _token, uint _amount) public { wallet.transferToBackupAccount(_token, _amount); } @param _token The ERC20 token the owner withdraws from @param _amount Amount to transfer @dev Withdraw funds to the user account. function transferToUserWithdrawalAccount(IERC20Token _token, uint _amount, IERC20Token _feesToken, uint _fee) public { wallet.transferToUserWithdrawalAccount(_token, _amount, _feesToken, _fee); } }
15,830,947
[ 1, 17, 279, 6835, 716, 8686, 279, 13706, 9230, 16, 2522, 635, 20296, 92, 16, 364, 3614, 394, 20296, 92, 729, 20126, 1071, 9230, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 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, 16351, 19656, 16936, 288, 203, 203, 565, 1450, 19656, 16936, 5664, 364, 19656, 16936, 5664, 18, 16936, 31, 203, 565, 19656, 16936, 5664, 18, 16936, 1071, 9230, 31, 203, 3639, 203, 565, 871, 12279, 774, 6248, 3032, 12, 2867, 389, 2316, 16, 1758, 389, 9572, 3032, 16, 2254, 389, 8949, 1769, 203, 565, 871, 12279, 774, 1299, 1190, 9446, 287, 3032, 12, 2867, 389, 2316, 16, 1758, 389, 1355, 1190, 9446, 287, 3032, 16, 2254, 389, 8949, 16, 1758, 389, 3030, 281, 1345, 16, 1758, 389, 3030, 281, 3032, 16, 2254, 389, 21386, 1769, 203, 565, 871, 28112, 1190, 9446, 287, 3032, 12, 2867, 389, 1355, 1190, 9446, 287, 3032, 1769, 203, 1377, 203, 3639, 632, 5206, 3885, 203, 203, 3639, 632, 891, 389, 9572, 3032, 4202, 432, 805, 3726, 1807, 2236, 358, 1366, 284, 19156, 358, 16, 316, 6088, 1625, 326, 729, 2236, 353, 203, 4766, 565, 15781, 578, 13557, 203, 3639, 632, 891, 389, 9497, 5411, 1021, 6835, 3726, 1758, 203, 3639, 632, 891, 389, 3030, 281, 3032, 540, 1021, 2236, 358, 7412, 1656, 281, 358, 7010, 203, 565, 445, 19656, 16936, 12, 2867, 389, 9572, 3032, 16, 1758, 389, 9497, 16, 1758, 389, 3030, 281, 3032, 13, 1071, 288, 203, 3639, 9230, 18, 2738, 16936, 24899, 9572, 3032, 16, 389, 9497, 16, 389, 3030, 281, 3032, 1769, 203, 565, 289, 203, 203, 540, 203, 3639, 632, 891, 389, 1355, 1190, 9446, 287, 3032, 4202, 1021, 729, 2236, 358, 598, 9446, 284, 19156, 358, 203, 540, 203, 3639, 632, 5206, 13274, 326, 2 ]
pragma solidity 0.5.16; import "../lib/protobuf/IssuanceData.sol"; import "../lib/protobuf/SupplementalLineItem.sol"; import "../lib/protobuf/TokenTransfer.sol"; import "./InstrumentInterface.sol"; /** * @title Base contract for instruments. */ contract InstrumentBase is InstrumentInterface { /** * @dev The event used to schedule contract events after specific time. * @param issuanceId The id of the issuance * @param timestamp After when the issuance should be notified * @param eventName The name of the custom event * @param eventPayload The payload the custom event */ event EventTimeScheduled( uint256 indexed issuanceId, uint256 timestamp, bytes32 eventName, bytes eventPayload ); /** * @dev The event used to schedule contract events after specific block. * @param issuanceId The id of the issuance * @param blockNumber After which block the issuance should be notified * @param eventName The name of the custom event * @param eventPayload The payload the custom event */ event EventBlockScheduled( uint256 indexed issuanceId, uint256 blockNumber, bytes32 eventName, bytes eventPayload ); /** * @dev The event used to track the creation of a new supplemental line item. * @param issuanceId The id of the issuance * @param itemId The id of the supplemental line item * @param itemType Type of the supplemental line item * @param state State of the supplemental line item * @param obligatorAddress The obligator of the supplemental line item * @param claimorAddress The claimor of the supplemental line item * @param tokenAddress The asset type of the supplemental line item * @param amount The asset amount of the supplemental line item * @param dueTimestamp When is the supplemental line item due */ event SupplementalLineItemCreated( uint256 indexed issuanceId, uint8 indexed itemId, SupplementalLineItem.Type itemType, SupplementalLineItem.State state, address obligatorAddress, address claimorAddress, address tokenAddress, uint256 amount, uint256 dueTimestamp ); /** * @dev The event used to track the update of an existing supplemental line item * @param issuanceId The id of the issuance * @param itemId The id of the supplemental line item * @param state The new state of the supplemental line item * @param reinitiatedTo The target supplemental line item if the current one is reinitiated */ event SupplementalLineItemUpdated( uint256 indexed issuanceId, uint8 indexed itemId, SupplementalLineItem.State state, uint8 reinitiatedTo ); // Scheduled custom events bytes32 internal constant ENGAGEMENT_DUE_EVENT = "engagement_due"; bytes32 internal constant ISSUANCE_DUE_EVENT = "issuance_due"; // Custom events bytes32 internal constant CANCEL_ISSUANCE_EVENT = "cancel_issuance"; bytes32 internal constant REPAY_ISSUANCE_FULL_EVENT = "repay_full"; // Common properties shared by all issuances uint256 internal _issuanceId; address internal _fspAddress; address internal _brokerAddress; address internal _instrumentEscrowAddress; address internal _issuanceEscrowAddress; address internal _priceOracleAddress; address internal _makerAddress; address internal _takerAddress; uint256 internal _creationTimestamp; uint256 internal _engagementTimestamp; uint256 internal _engagementDueTimestamp; uint256 internal _issuanceDueTimestamp; uint256 internal _settlementTimestamp; IssuanceProperties.State internal _state; // List of supplemental line items mapping(uint8 => SupplementalLineItem.Data) internal _supplementalLineItems; uint8[] internal _supplementalLineItemIds; /** * @dev Initializes an issuance with common parameters. * @param issuanceId ID of the issuance. * @param fspAddress Address of the FSP who creates the issuance. * @param brokerAddress Address of the instrument broker. * @param instrumentEscrowAddress Address of the instrument escrow. * @param issuanceEscrowAddress Address of the issuance escrow. * @param priceOracleAddress Address of the price oracle. */ function initialize( uint256 issuanceId, address fspAddress, address brokerAddress, address instrumentEscrowAddress, address issuanceEscrowAddress, address priceOracleAddress ) public { require(_issuanceId == 0, "Already initialized"); require(issuanceId != 0, "Issuance ID not set"); require(fspAddress != address(0x0), "FSP not set"); require( instrumentEscrowAddress != address(0x0), "Instrument Escrow not set" ); require( issuanceEscrowAddress != address(0x0), "Issuance Escrow not set" ); require(priceOracleAddress != address(0x0), "Price Oracle not set"); _issuanceId = issuanceId; _fspAddress = fspAddress; _brokerAddress = brokerAddress; _instrumentEscrowAddress = instrumentEscrowAddress; _issuanceEscrowAddress = issuanceEscrowAddress; _priceOracleAddress = priceOracleAddress; _state = IssuanceProperties.State.Initiated; } /** * @dev Checks whether the issuance is terminated. No futher action is taken on a terminated issuance. */ function isTerminated() public view returns (bool) { return _state == IssuanceProperties.State.Unfunded || _state == IssuanceProperties.State.Cancelled || _state == IssuanceProperties.State.CompleteNotEngaged || _state == IssuanceProperties.State.CompleteEngaged || _state == IssuanceProperties.State.Delinquent; } /** * @dev Create a new issuance of the financial instrument */ function createIssuance( address, /** callerAddress */ bytes memory /** makerParametersData */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev A taker engages to the issuance */ function engageIssuance( address, /** callerAddress */ bytes memory /** takerParameters */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev An account has made an ERC20 token deposit to the issuance */ function processTokenDeposit( address, /** callerAddress */ address, /** tokenAddress */ uint256 /** amount */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev An account has made an ERC20 token withdraw from the issuance */ function processTokenWithdraw( address, /** callerAddress */ address, /** tokenAddress */ uint256 /** amount */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev A custom event is triggered. */ function processCustomEvent( address, /** callerAddress */ bytes32, /** eventName */ bytes memory /** eventPayload */ ) public returns (bytes memory) { revert("Unsupported operation"); } /** * @dev Get custom data. */ function getCustomData( address, /** callerAddress */ bytes32 /** dataName */ ) public view returns (bytes memory) { revert("Unsupported operation"); } /** * @dev Returns the common properties about the issuance. */ function _getIssuanceProperties() internal view returns (IssuanceProperties.Data memory) { SupplementalLineItem.Data[] memory supplementalLineItems = new SupplementalLineItem.Data[]( _supplementalLineItemIds.length ); for (uint256 i = 0; i < _supplementalLineItemIds.length; i++) { supplementalLineItems[i] = _supplementalLineItems[_supplementalLineItemIds[i]]; } return IssuanceProperties.Data({ issuanceId: _issuanceId, makerAddress: _makerAddress, takerAddress: _takerAddress, engagementDueTimestamp: _engagementDueTimestamp, issuanceDueTimestamp: _issuanceDueTimestamp, creationTimestamp: _creationTimestamp, engagementTimestamp: _engagementTimestamp, settlementTimestamp: _settlementTimestamp, issuanceProxyAddress: address(this), issuanceEscrowAddress: _issuanceEscrowAddress, state: _state, supplementalLineItems: supplementalLineItems }); } /** * @dev Create a new inbound transfer action. */ function _createInboundTransfer( address account, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.Inbound, fromAddress: account, toAddress: account, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create a new outbound transfer action. */ function _createOutboundTransfer( address account, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.Outbound, fromAddress: account, toAddress: account, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create a new intra-issuance transfer action. */ function _createIntraIssuanceTransfer( address fromAddress, address toAddress, address tokenAddress, uint256 amount, bytes32 action ) internal pure returns (Transfer.Data memory) { Transfer.Data memory transfer = Transfer.Data({ transferType: Transfer.Type.IntraIssuance, fromAddress: fromAddress, toAddress: toAddress, tokenAddress: tokenAddress, amount: amount, action: action }); return transfer; } /** * @dev Create new payable for the issuance. */ function _createNewPayable( uint8 id, address obligatorAddress, address claimorAddress, address tokenAddress, uint256 amount, uint256 dueTimestamp ) internal { require( _supplementalLineItems[id].state == SupplementalLineItem.State.UnknownState, "Item exists" ); _supplementalLineItemIds.push(id); _supplementalLineItems[id] = SupplementalLineItem.Data({ id: id, lineItemType: SupplementalLineItem.Type.Payable, state: SupplementalLineItem.State.Unpaid, obligatorAddress: obligatorAddress, claimorAddress: claimorAddress, tokenAddress: tokenAddress, amount: amount, dueTimestamp: dueTimestamp, reinitiatedTo: 0 }); emit SupplementalLineItemCreated( _issuanceId, id, SupplementalLineItem.Type.Payable, SupplementalLineItem.State.Unpaid, obligatorAddress, claimorAddress, tokenAddress, amount, dueTimestamp ); } /** * @dev Updates the existing payable for the issuance. */ function _updatePayable( uint8 id, SupplementalLineItem.State state, uint8 reinitiatedTo ) internal { require( _supplementalLineItems[id].state != SupplementalLineItem.State.UnknownState, "Item not exists" ); _supplementalLineItems[id].state = state; _supplementalLineItems[id].reinitiatedTo = reinitiatedTo; emit SupplementalLineItemUpdated(_issuanceId, id, state, reinitiatedTo); } }
* @dev Get custom data./
function getCustomData( address, /** callerAddress */ bytes32 /** dataName */ ) public view returns (bytes memory) { revert("Unsupported operation"); }
12,957,177
[ 1, 967, 1679, 501, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 12736, 751, 12, 203, 3639, 1758, 16, 1783, 4894, 1887, 1195, 203, 3639, 1731, 1578, 1783, 501, 461, 1195, 203, 565, 262, 1071, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 15226, 2932, 8544, 1674, 8863, 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 ]
//Address: 0xc4785a90e3d8d3191625ccf82623cb4daf5d6b0d //Contract name: NETRico //Balance: 0 Ether //Verification Date: 4/4/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.20; /** * @title ICO SALE CONTRACT * @dev ERC-20 Token Standard Compliant */ /** * @title SafeMath by OpenZeppelin * @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) { uint256 c = a / b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } /** * @title Fiat currency contract * @dev This contract will return the value of 0.01$ ETH in wei */ contract FiatContract { function EUR(uint _id) constant public returns (uint256); } /** * @title DateTime contract * @dev This contract will return the unix value of any date */ contract DateTimeAPI { function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) constant public returns (uint timestamp); } /** * @title ERC20 Token interface */ contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } /** * @title NETRico sale main contract */ contract NETRico { FiatContract price = FiatContract(0x8055d0504666e2B6942BeB8D6014c964658Ca591); // MAINNET ADDRESS DateTimeAPI dateTimeContract = DateTimeAPI(0x1a6184CD4C5Bea62B0116de7962EE7315B7bcBce);//Main using SafeMath for uint256; //This sale have 5 stages enum State { Stage1, Stage2, Stage3, Stage4, Successful } //public variables State public state = State.Stage1; //Set initial stage uint256 public startTime = dateTimeContract.toTimestamp(2018,4,1,0); //From Apr 1 2018 00:00 uint256 public deadline = dateTimeContract.toTimestamp(2019,3,27,0); //Stop Mar 27 2019 00:00 uint256 public totalRaised; //eth in wei uint256 public totalDistributed; //tokens distributed uint256 public completedAt; //Time stamp when the sale finish token public tokenReward; //Address of the valid token used as reward address public creator; //Address of the contract deployer string public campaignUrl; //Web site of the campaign string public version = '2'; //events for log event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogFundingSuccessful(uint _totalRaised); event LogFunderInitialized( address _creator, string _url); event LogContributorsPayout(address _addr, uint _amount); modifier notFinished() { require(state != State.Successful); _; } /** * @notice NETRico constructor * @param _campaignUrl is the ICO _url * @param _addressOfTokenUsedAsReward is the token totalDistributed */ function NETRico (string _campaignUrl, token _addressOfTokenUsedAsReward) public { creator = 0xB987B463c7573f0B7b6eD7cc8E5Fab9042272065; //creator = msg.sender; campaignUrl = _campaignUrl; tokenReward = token(_addressOfTokenUsedAsReward); emit LogFunderInitialized( creator, campaignUrl ); } /** * @notice contribution handler */ function contribute() public notFinished payable { require(now >= startTime); uint256 tokenBought; //Variable to store amount of tokens bought uint256 tokenPrice = price.EUR(0); //1 cent value in wei totalRaised = totalRaised.add(msg.value); //Save the total eth totalRaised (in wei) tokenPrice = tokenPrice.mul(2); //0.02$ EUR value in wei tokenPrice = tokenPrice.div(10 ** 8); //Change base 18 to 10 tokenBought = msg.value.div(tokenPrice); //Base 18/ Base 10 = Base 8 tokenBought = tokenBought.mul(10 ** 10); //Base 8 to Base 18 require(tokenBought >= 100 * 10 ** 18); //Minimum 100 base tokens //Bonus calculation if (state == State.Stage1){ tokenBought = tokenBought.mul(2); //+100% } else if (state == State.Stage2){ tokenBought = tokenBought.mul(175); tokenBought = tokenBought.div(100); //+75% } else if (state == State.Stage3){ tokenBought = tokenBought.mul(15); tokenBought = tokenBought.div(10); //+50% } else if (state == State.Stage4){ tokenBought = tokenBought.mul(125); tokenBought = tokenBought.div(100); //+25% } totalDistributed = totalDistributed.add(tokenBought); //Save to total tokens distributed tokenReward.transfer(msg.sender,tokenBought); //Send Tokens creator.transfer(msg.value); // Send ETH to creator emit LogBeneficiaryPaid(creator); //LOGS emit LogFundingReceived(msg.sender, msg.value, totalRaised); emit LogContributorsPayout(msg.sender,tokenBought); checkIfFundingCompleteOrExpired(); } /** * @notice check status */ function checkIfFundingCompleteOrExpired() public { if(now > deadline && state != State.Successful){ state = State.Successful; //Sale becomes Successful completedAt = now; //ICO finished emit LogFundingSuccessful(totalRaised); //we log the finish finished(); } else if(state == State.Stage3 && now > dateTimeContract.toTimestamp(2018,12,27,0)){ state = State.Stage4; } else if(state == State.Stage2 && now > dateTimeContract.toTimestamp(2018,9,28,0)){ state = State.Stage3; } else if(state == State.Stage1 && now > dateTimeContract.toTimestamp(2018,6,30,0)){ state = State.Stage2; } } /** * @notice Function for closure handle */ function finished() public { //When finished eth are transfered to creator require(state == State.Successful); //Only when sale finish uint256 remainder = tokenReward.balanceOf(this); //Remaining tokens on contract //Funds send to creator if any if(address(this).balance > 0) { creator.transfer(address(this).balance); emit LogBeneficiaryPaid(creator); } tokenReward.transfer(creator,remainder); //remainder tokens send to creator emit LogContributorsPayout(creator, remainder); } /** * @notice Function to claim any token stuck on contract */ function claimTokens(token _address) public{ require(state == State.Successful); //Only when sale finish require(msg.sender == creator); uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(creator,remainder); //Transfer tokens to creator } /** * @notice Function to handle eth transfers * @dev BEWARE: if a call to this functions doesn't have * enought gas, transaction could not be finished */ function() public payable { contribute(); } }
* @notice Function to claim any token stuck on contract/
function claimTokens(token _address) public{ require(msg.sender == creator); }
1,060,583
[ 1, 2083, 358, 7516, 1281, 1147, 384, 9031, 603, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 5157, 12, 2316, 389, 2867, 13, 1071, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 11784, 1769, 203, 203, 540, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // https://kanon.art - K21 // https://daemonica.io // // // [email protected]@@@@@@@@@@$$$ // [email protected]@@@@@$$$$$$$$$$$$$$## // $$$$$$$$$$$$$$$$$#########*** // $$$$$$$$$$$$$$$#######**!!!!!! // ##$$$$$$$$$$$$#######****!!!!========= // ##$$$$$$$$$#$#######*#***!!!=!===;;;;; // *#################*#***!*!!======;;;::: // ################********!!!!====;;;:::~~~~~ // **###########******!!!!!!==;;;;::~~~--,,,-~ // ***########*#*******!*!!!!====;;;::::~~-,,......,- // ******#**********!*!!!!=!===;;::~~~-,........ // ***************!*!!!!====;;:::~~-,,.......... // !************!!!!!!===;;::~~--,............ // !!!*****!!*!!!!!===;;:::~~--,,.......... // =!!!!!!!!!=!==;;;::~~-,,........... // =!!!!!!!!!====;;;;:::~~--,........ // ==!!!!!!=!==;=;;:::~~--,...:~~--,,,.. // ===!!!!!=====;;;;;:::~~~--,,..#*=;;:::~--,. // ;=============;;;;;;::::~~~-,,...$$###==;;:~--. // :;;==========;;;;;;::::~~~--,,[email protected]@$$##*!=;:~-. // :;;;;;===;;;;;;;::::~~~--,,...$$$$#*!!=;~- // :;;;;;;;;;;:::::~~~~---,,...!*##**!==;~, // :::;:;;;;:::~~~~---,,,...~;=!!!!=;;:~. // ~:::::::::::::~~~~~---,,,....-:;;=;;;~, // ~~::::::::~~~~~~~-----,,,......,~~::::~-. // -~~~~~~~~~~~~~-----------,,,.......,-~~~~~,. // ---~~~-----,,,,,........,---,. // ,,--------,,,,,,......... // .,,,,,,,,,,,,...... // ............... // ......... pragma solidity ^0.8.0; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./OccultMath.sol"; import "./Helpers.sol"; interface IBase64 is IERC721Enumerable, IERC721Metadata {} interface IDaemonica { function getTau(address _hodler) external view returns (string[] memory); function getTheta(uint256 _tokenId, uint8 _modulo, string[] memory _tau) external view returns (uint8[8][8] memory); function isQualified(address _hodler) external view returns (bool); } /** @title Daemonica contract * @author @0xAnimist * @notice "Daemonica generates an ever-changing 8 x 8 numerical matrix from base64-encoded * onchain art. Each matrix is associated with an "Entity," which in turn can cast "Xe_ntities." * The n dimensional relationships that exist within and between each Entity and Xe_ntity can be * freely interpreted and understood. Use Daemonica however you wish." –artist */ contract Daemonica is Ownable, ReentrancyGuard { uint8 public totalDims = 0; uint8 public totalAddedDims = 0; uint8 public maxAddableDims = 128; mapping (string => address) public dimAdder; uint8 public totalOwnerAddedDims = 0; uint8 public maxOwnerAddableDims = 128; bool public presale = true; address public artist; uint256 public artistBalance = 0; uint256 public ownerBalance = 0; mapping (string => IBase64) private dims; mapping (uint8 => string) private symbolStringByIndex; mapping (string => uint8) private symbolIndexByString; /** @notice Allows only the artist to broadcast a message * @param _artist Artists's address * @param _message Artist's message */ event Broadcast(address indexed _artist, string _message); /** @notice Only the artist can call function */ modifier onlyArtist() { require(artist == _msgSender(), "caller is not the artist"); _; } /** @notice Only the artist or owner can call function */ modifier onlyAdmin() { require(artist == _msgSender() || owner() == _msgSender(), "caller is not the artist or owner"); _; } /** @notice Requires dim with symbol _symbol to be initialized * @param _symbol Symbol associated with the dim's contract */ modifier dimExists(string memory _symbol) { require(Helpers.compareStrings(symbolStringByIndex[symbolIndexByString[_symbol]],_symbol), "dim not exist"); _; } /** @notice Allows only the artist to broadcast a message * @param _message Artist's message */ function artistBroadcast(string memory _message) external onlyArtist { emit Broadcast(msg.sender, _message); } /** @notice Allows the owner to set the presale flag * @param _value the new value */ function setPresale(bool _value) external onlyOwner { presale = _value; } /** @notice Returns lists of all dims by symbol and address * @dev different contracts with the same symbol cannot be registered, only the first registered will be accepted * @return string array of each dim symbol * @return address array of each dim contract address */ function getDims() external view returns (string[] memory, address[] memory) { string[] memory symbols = new string[](totalDims); address[] memory addresses = new address[](totalDims); for(uint8 i = 0; i < totalDims; i++){ symbols[i] = symbolStringByIndex[i]; addresses[i] = address(dims[symbols[i]]); } return (symbols, addresses); } /** @notice Registers a new dim * @dev different contracts with the same symbol cannot be registered, only the first registered will be accepted * @param _address Contract address of dim to register */ function registerDim(address _address) internal { IBase64 dim = IBase64(_address); //name the new dim symbolically and increment the dims counter string memory symbol = dim.symbol(); require(!Helpers.compareStrings(dim.symbol(), ""), "requires symbol"); require(!Helpers.compareStrings(symbolStringByIndex[symbolIndexByString[symbol]],symbol), "symbol already registered"); //ensure the new dim is base64 encoded require(isValidLootverseURI(dim.tokenURI(1)));//test it against the first token symbolStringByIndex[totalDims] = symbol; symbolIndexByString[symbol] = totalDims; totalDims++; dims[symbol] = dim; dimAdder[symbol] = _msgSender(); } /** @notice Allows owner to add a dim with a quota of maxOwnerAddableDims * @param _address Contract address of dim to register */ function adminAddDim(address _address) external onlyAdmin { require(totalOwnerAddedDims < maxOwnerAddableDims, "owner quota exceeded"); registerDim(_address); totalOwnerAddedDims++; } /** @notice Anyone can add a valid dim for 1 ether * @param _address Contract address of dim to register */ function addDim(address _address) external payable nonReentrant { require(!presale, "not yet"); require(msg.value >= 1 ether, "costs 1 eth"); require(totalAddedDims < maxAddableDims, "public quota exceeded"); registerDim(_address); totalAddedDims++; ownerBalance += msg.value/2; artistBalance += msg.value/2;//TODO (msg.value - msg.value/2); } /** @notice Refunds a dimAdder if owner has to delete the dim the added in case * of emergency * @param _symbol Symbol of the dim being removed that needs refunding */ function refund(string memory _symbol) internal { require(address(this).balance >= 1 ether, "owner cannot afford refund"); payable(dimAdder[_symbol]).transfer(1 ether); uint256 half = (1 ether)/2; if(ownerBalance >= half){ if(artistBalance >= half){ ownerBalance -= half; artistBalance -= half; }else{ ownerBalance -= (1 ether) - artistBalance; artistBalance = 0; } }else{ artistBalance -= (1 ether) - ownerBalance; ownerBalance = 0; } } /** @notice Allows owner to remove a dim and refund the dimAdder * @dev Emergency use only * @param _symbol Symbol of the dim to remove */ function adminRemoveDim(string memory _symbol) external onlyAdmin dimExists(_symbol) { require(totalDims > 0, "no dims"); refund(_symbol); delete(dims[_symbol]);//delete the interface //refactor the mappings for(uint8 i = symbolIndexByString[_symbol]; i < totalDims; i++){ symbolStringByIndex[i] = symbolStringByIndex[i+1]; symbolIndexByString[symbolStringByIndex[i]] = i; } //delete the mappings delete(symbolIndexByString[_symbol]); delete(symbolStringByIndex[totalDims]); //decrement the count totalDims--; } /** @notice Returns true if the given tokenURI() return value has a valid base64 header, payload, and its contract has a valid symbol * @param _str Return value from tokenURI() to test * @return true or false */ function isValidLootverseURI(string memory _str) internal pure returns (bool) { require(Helpers.compareStrings("data:application/json;base64,", Helpers.substring(_str, 0, 29)), 'Invalid prefix'); string memory payload = Helpers.substring(_str, 29, 0); require( OccultMath.isValidBase64String(payload), "non-base64 chars"); return true; } /** @notice Returns true if _hodler holds tokens from any dim in _animolist * @param _hodler would be _hodler * @return True or false */ function isQualified(address _hodler) external view returns (bool){ for(uint8 i = 0; i < totalDims; i++){ if(dims[symbolStringByIndex[i]].balanceOf(_hodler) > 0){ return true; } } return false; } /** @notice 𝜏 = tau, a rarely used Greek symbol, *facta bruta* :( 𝜏 symbolizes ( life | regeneration | resurrection | the power to find new life paths or choices )+. A striking phonetic relationship exists between 𝜏 and "tao", the Chinese term for ( the way | the true path | inner compass )+. *Hic et nunc*, the Daemonican way is death * life, or θ𝜏=X(ξ). * @dev Returns any dims in which the _hodler owns at least one token of any tokenId * @param _hodler entity hodler * @return A string array of the symbols of one or more tokens from each dim held by the hodler */ function getTau(address _hodler) public view returns (string[] memory){ string[] memory tau; uint8 count = 0; if(_hodler == address(0)){//no hodler, default to first dim tau = new string[](1); tau[count++] = symbolStringByIndex[0]; return tau; }else{ tau = new string[](totalDims); for(uint8 i = 0; i < totalDims; i++){ if(dims[symbolStringByIndex[i]].balanceOf(_hodler) > 0){ tau[count++] = symbolStringByIndex[i]; } } if(count == 0){//default to first dim string[] memory output = new string[](1); output[0] = symbolStringByIndex[0]; return output; }else{//splice to length string[] memory output = new string[](count); for(uint8 i = 0; i < count; i++){ output[i] = tau[i]; } return output; } } } /** @notice θ = theta, symbol of change in angle or rotation. *Thanatos* (death) hides in this symbol. There is no ξ without θ, no *existentialia* without change. θ is also therefore a talismanic sign for passage to the “underworld”, to a realm closer to life’s origins. * @dev Returns theta, the 8x8 base-_modulo frequency matrix of an entity * @param _tokenId tokenId of the entity being queried * @param _modulo caps all values at base-_modulo * @param _tau tau is the dimensions of _tokenId's hodler */ function getTheta(uint256 _tokenId, uint8 _modulo, string[] memory _tau) external view returns (uint8[8][8] memory) { bytes[] memory bytePayloads = new bytes[](_tau.length); for(uint8 i = 0; i < _tau.length; i++){ bytePayloads[i] = bytes(Helpers.substring(dims[_tau[i]].tokenURI(_tokenId), 29, 0)); } uint8[8][8] memory thetas = OccultMath.sixtyFourier(bytePayloads, _modulo); return thetas; } /** @notice Allows owner to withdraw available balance */ function ownerWithdrawAvailableBalance() public nonReentrant onlyOwner { uint256 b = ownerBalance; ownerBalance = 0; payable(msg.sender).transfer(b); } /** @notice Allows artist to withdraw available balance */ function artistWithdrawAvailableBalance() public nonReentrant onlyArtist { uint256 b = artistBalance; artistBalance = 0; payable(msg.sender).transfer(b); } /** @notice Daemonica constructor * @param _artist The Ethereum address of the artist */ constructor (address _artist) { artist = _artist; } }
default to first dim
if(count == 0){
98,043
[ 1, 1886, 358, 1122, 2464, 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, 1377, 309, 12, 1883, 422, 374, 15329, 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 ]
./full_match/1/0xd1Bfc5bea5c5B72fe1a8311ce9dfF20B74A0d4aC/sources/contracts/MetalorianSwap.sol
@param user user trade address @param protocolFee incoming amount @param amountIn incoming amount @param amountOut output amount
event Swap( address indexed user, uint protocolFee, uint amountIn, uint amountOut);
9,693,751
[ 1, 1355, 729, 18542, 1758, 225, 1771, 14667, 6935, 3844, 225, 3844, 382, 6935, 3844, 225, 3844, 1182, 876, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 12738, 12, 1758, 8808, 729, 16, 2254, 1771, 14667, 16, 2254, 3844, 382, 16, 2254, 3844, 1182, 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 ]
pragma solidity ^0.6.7; import "interfaces/chainlink/AggregatorV3Interface.sol"; import "interfaces/digg/IMedianOracle.sol"; import "deps/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract ChainlinkOracle is OwnableUpgradeable { AggregatorV3Interface internal priceFeed; event UpdatePushed(IMedianOracle medianOracle, uint256 price); IMedianOracle internal _medianOracle; /** * Network: Ethereum * Aggregator: DIGG/BTC * Address: 0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685 */ constructor(IMedianOracle medianOracle) public { __Ownable_init(); uint256 decimals = 18; _medianOracle = medianOracle; priceFeed = AggregatorV3Interface(0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685); } /** * Returns the latest price */ function getThePrice() public returns (int256) { (uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound) = priceFeed.latestRoundData(); price = price * (10**10); _medianOracle.pushReport(uint256(price)); emit UpdatePushed(_medianOracle, uint256(price)); return price; } }
* Network: Ethereum Aggregator: DIGG/BTC Address: 0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685/
constructor(IMedianOracle medianOracle) public { __Ownable_init(); uint256 decimals = 18; _medianOracle = medianOracle; priceFeed = AggregatorV3Interface(0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685); }
5,361,239
[ 1, 3906, 30, 512, 18664, 379, 10594, 639, 30, 24313, 43, 19, 38, 15988, 5267, 30, 374, 92, 24, 2643, 69, 26, 39, 10689, 10160, 25, 38, 28, 5324, 6162, 2539, 74, 6840, 42, 20, 70, 28, 39, 21, 71, 9470, 7414, 71, 28, 70, 2313, 7140, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 3445, 329, 2779, 23601, 12644, 23601, 13, 1071, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 2254, 5034, 15105, 273, 6549, 31, 203, 3639, 389, 22410, 23601, 273, 12644, 23601, 31, 203, 3639, 6205, 8141, 273, 10594, 639, 58, 23, 1358, 12, 20, 92, 24, 2643, 69, 26, 39, 10689, 10160, 25, 38, 28, 5324, 6162, 2539, 74, 6840, 42, 20, 70, 28, 39, 21, 71, 9470, 7414, 71, 28, 70, 2313, 7140, 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 ]
./partial_match/1/0x947a2e766F5e7A6002F02c08eAbE6f236Cc41C9B/sources/QuantumCreatures.sol
Mark listing as inactive
tokenListings[_tokenIds[i]].isListed = false;
3,903,061
[ 1, 3882, 11591, 487, 16838, 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, 5411, 1147, 682, 899, 63, 67, 2316, 2673, 63, 77, 65, 8009, 291, 682, 329, 273, 629, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; /* TenX Reseller ======================== Resells TenX tokens from the crowdsale before transfers are enabled. Author: /u/Cintix */ // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 // Well, almost. PAY tokens throw on transfer failure instead of returning false. contract ERC20 { function transfer(address _to, uint _value); function balanceOf(address _owner) constant returns (uint balance); } // Interface to TenX ICO Contract contract MainSale { function createTokens(address recipient) payable; } contract Reseller { // Store the amount of PAY claimed by each account. mapping (address => uint256) public pay_claimed; // Total claimed PAY of all accounts. uint256 public total_pay_claimed; // The TenX Token Sale address. MainSale public sale = MainSale(0xd43D09Ec1bC5e57C8F3D0c64020d403b04c7f783); // TenX Token (PAY) Contract address. ERC20 public token = ERC20(0xB97048628DB6B661D4C2aA833e95Dbe1A905B280); // The developer address. address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e; // Buys PAY for the contract with user funds. function buy() payable { // Transfer received funds to the TenX crowdsale contract to buy tokens. sale.createTokens.value(msg.value)(address(this)); } // Withdraws PAY claimed by the user. function withdraw() { // Store the user&#39;s amount of claimed PAY as the amount of PAY to withdraw. uint256 pay_to_withdraw = pay_claimed[msg.sender]; // Update the user&#39;s amount of claimed PAY first to prevent recursive call. pay_claimed[msg.sender] = 0; // Update the total amount of claimed PAY. total_pay_claimed -= pay_to_withdraw; // Send the user their PAY. Throws on failure to prevent loss of funds. token.transfer(msg.sender, pay_to_withdraw); } // Claims PAY at a price determined by the block number. function claim() payable { // Verify ICO is over. if(block.number < 3930000) throw; // Calculate current sale price (PAY per ETH) based on block number. uint256 pay_per_eth = (block.number - 3930000) / 10; // Calculate amount of PAY user can purchase. uint256 pay_to_claim = pay_per_eth * msg.value; // Retrieve current PAY balance of contract. uint256 contract_pay_balance = token.balanceOf(address(this)); // Verify the contract has enough remaining unclaimed PAY. if((contract_pay_balance - total_pay_claimed) < pay_to_claim) throw; // Update the amount of PAY claimed by the user. pay_claimed[msg.sender] += pay_to_claim; // Update the total amount of PAY claimed by all users. total_pay_claimed += pay_to_claim; // Send the funds to the developer instead of leaving them in the contract. developer.transfer(msg.value); } // Default function. Called when a user sends ETH to the contract. function () payable { // If the user sent a 0 ETH transaction, withdraw their PAY. if(msg.value == 0) { withdraw(); } // If the user sent ETH, claim PAY with it. else { claim(); } } }
Claims PAY at a price determined by the block number. Verify ICO is over. Calculate current sale price (PAY per ETH) based on block number. Calculate amount of PAY user can purchase. Retrieve current PAY balance of contract. Verify the contract has enough remaining unclaimed PAY. Update the amount of PAY claimed by the user. Update the total amount of PAY claimed by all users. Send the funds to the developer instead of leaving them in the contract.
function claim() payable { if(block.number < 3930000) throw; uint256 pay_per_eth = (block.number - 3930000) / 10; uint256 pay_to_claim = pay_per_eth * msg.value; uint256 contract_pay_balance = token.balanceOf(address(this)); if((contract_pay_balance - total_pay_claimed) < pay_to_claim) throw; pay_claimed[msg.sender] += pay_to_claim; total_pay_claimed += pay_to_claim; developer.transfer(msg.value); }
2,246,903
[ 1, 15925, 25095, 622, 279, 6205, 11383, 635, 326, 1203, 1300, 18, 8553, 467, 3865, 353, 1879, 18, 9029, 783, 272, 5349, 6205, 261, 11389, 1534, 512, 2455, 13, 2511, 603, 1203, 1300, 18, 9029, 3844, 434, 25095, 729, 848, 23701, 18, 10708, 783, 25095, 11013, 434, 6835, 18, 8553, 326, 6835, 711, 7304, 4463, 6301, 80, 4581, 329, 25095, 18, 2315, 326, 3844, 434, 25095, 7516, 329, 635, 326, 729, 18, 2315, 326, 2078, 3844, 434, 25095, 7516, 329, 635, 777, 3677, 18, 2479, 326, 284, 19156, 358, 326, 8751, 3560, 434, 15086, 2182, 316, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 7516, 1435, 8843, 429, 288, 203, 565, 309, 12, 2629, 18, 2696, 411, 890, 11180, 2787, 13, 604, 31, 203, 565, 2254, 5034, 8843, 67, 457, 67, 546, 273, 261, 2629, 18, 2696, 300, 890, 11180, 2787, 13, 342, 1728, 31, 203, 565, 2254, 5034, 8843, 67, 869, 67, 14784, 273, 8843, 67, 457, 67, 546, 380, 1234, 18, 1132, 31, 203, 565, 2254, 5034, 6835, 67, 10239, 67, 12296, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 309, 12443, 16351, 67, 10239, 67, 12296, 300, 2078, 67, 10239, 67, 14784, 329, 13, 411, 8843, 67, 869, 67, 14784, 13, 604, 31, 203, 565, 8843, 67, 14784, 329, 63, 3576, 18, 15330, 65, 1011, 8843, 67, 869, 67, 14784, 31, 203, 565, 2078, 67, 10239, 67, 14784, 329, 1011, 8843, 67, 869, 67, 14784, 31, 203, 565, 8751, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 225, 289, 203, 21281, 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 ]
pragma ton-solidity >= 0.36.0; pragma AbiHeader expire; pragma AbiHeader time; import "Base.sol"; import "IVote.sol"; contract Juror is Base { function recordVote(address contest, HiddenEvaluation hiddenVote) external pure signed { IVote(contest).recordVote{value: 0.2 ton, flag: 1}(hiddenVote); } function revealVote(address contest, Evaluation evaluation) external pure signed { IVote(contest).revealVote{value: 0.2 ton, flag: 1}(evaluation); } function _validateScore(Evaluation evaluation) private pure returns (uint8 score) { score = evaluation.score; if (evaluation.voteType == VoteType.For) { if (score == 0) { score = 1; } else if (score > 10) { score = 10; } } else { score = 0; } } function hashEvaluation(Evaluation evaluation) public pure returns (uint hash) { TvmBuilder builder; builder.store(evaluation.entryId, uint8(evaluation.voteType), evaluation.score, evaluation.comment); TvmCell cell = builder.toCell(); hash = tvm.hash(cell); } /* Combine juror and entry IDs to index the mark */ function _markId(uint8 jurorId, uint8 entryId) private inline pure returns (uint16 markId) { markId = uint16(jurorId * (1 << 8) + entryId); } function _recordVote(uint8 jurorId, Evaluation evaluation) private pure inline { } }
Combine juror and entry IDs to index the mark */
function _markId(uint8 jurorId, uint8 entryId) private inline pure returns (uint16 markId) { markId = uint16(jurorId * (1 << 8) + entryId); }
12,945,271
[ 1, 21720, 525, 295, 280, 471, 1241, 7115, 358, 770, 326, 2267, 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 ]
[ 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, 389, 3355, 548, 12, 11890, 28, 525, 295, 280, 548, 16, 2254, 28, 1241, 548, 13, 3238, 6370, 16618, 1135, 261, 11890, 2313, 2267, 548, 13, 288, 203, 3639, 2267, 548, 273, 2254, 2313, 12, 78, 295, 280, 548, 380, 261, 21, 2296, 1725, 13, 397, 1241, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma ton-solidity >= 0.45.0; pragma AbiHeader expire; pragma AbiHeader pubkey; pragma AbiHeader time; import "../interfaces/IRootTokenContract.sol"; import "../interfaces/ITONTokenWallet.sol"; import "../interfaces/IExpectedWalletAddressCallback.sol"; import "../interfaces/IBurnableByOwnerTokenWallet.sol"; import "../interfaces/IDEXConnector.sol"; import "../interfaces/IDEXConnect.sol"; contract DEXConnector is IExpectedWalletAddressCallback, IDEXConnector { // so - sharding optimization uint256 static public soUINT; address static public dexclient; // Grams constants uint128 constant GRAMS_TO_ROOT = 1.5 ton; uint128 constant GRAMS_TO_NEW_WALLET = 0.75 ton; address public drivenRoot; address public driven; bool public statusConnected; // Modifier that allows public function to accept any external calls. modifier alwaysAccept { tvm.accept(); _; } modifier checkOwnerAndAccept { // Check that message from contract owner. require(msg.sender == dexclient, 101); tvm.accept(); _; } constructor() public checkOwnerAndAccept { statusConnected = false; } /* * Public functions */ // Function to get Quotient of division function getQuotient(uint128 arg0, uint128 arg1, uint128 arg2) private inline pure returns (uint128) { (uint128 quotient, ) = math.muldivmod(arg0, arg1, arg2); return quotient; } // Function to get Remainder of division function getRemainder(uint128 arg0, uint128 arg1, uint128 arg2) private inline pure returns (uint128) { (, uint128 remainder) = math.muldivmod(arg0, arg1, arg2); return remainder; } // Function to deployEmptyWallet function deployEmptyWallet(address root) public override { require(msg.sender == dexclient, 101); require(msg.value >= GRAMS_TO_ROOT * 2, 103); tvm.rawReserve(address(this).balance - msg.value, 2); if (!statusConnected) { drivenRoot = root; TvmCell bodyD = tvm.encodeBody(IRootTokenContract(root).deployEmptyWallet, GRAMS_TO_NEW_WALLET, 0, address(this), dexclient); root.transfer({value:GRAMS_TO_ROOT, bounce:true, body:bodyD}); TvmCell bodyA = tvm.encodeBody(IRootTokenContract(root).sendExpectedWalletAddress, 0, address(this), address(this)); root.transfer({value:GRAMS_TO_ROOT, bounce:true, body:bodyA}); dexclient.transfer({value: 0, bounce:true, flag: 128}); } else { dexclient.transfer({value: 0, bounce:true, flag: 128}); } } // Function for callback with address from Root Token Contract function expectedWalletAddressCallback(address wallet, uint256 wallet_public_key, address owner_address) public override { require(msg.sender == drivenRoot && wallet_public_key == 0 && owner_address == address(this), 102); tvm.rawReserve(address(this).balance - msg.value, 2); statusConnected = true; driven = wallet; TvmCell body = tvm.encodeBody(IDEXConnect(dexclient).connectCallback, wallet); dexclient.transfer({value: 0, bounce:true, flag: 128, body:body}); } // Function for setTransferCallback function setTransferCallback() public override { require(msg.sender == dexclient, 101); tvm.rawReserve(address(this).balance - msg.value, 2); TvmCell body = tvm.encodeBody(ITONTokenWallet(driven).setReceiveCallback, dexclient, true); driven.transfer({value: 0, bounce:true, flag: 128, body:body}); } // Function for setBouncedCallback function setBouncedCallback() public override { require(msg.sender == dexclient, 101); tvm.rawReserve(address(this).balance - msg.value, 2); TvmCell body = tvm.encodeBody(ITONTokenWallet(driven).setBouncedCallback, dexclient); driven.transfer({value: 0, bounce:true, flag: 128, body:body}); } // Function for transfer tokens by connector owner function transfer(address to, uint128 tokens, TvmCell payload) public override { require(msg.sender == dexclient, 101); tvm.rawReserve(address(this).balance - msg.value, 2); TvmCell body = tvm.encodeBody(ITONTokenWallet(driven).transfer, to, tokens, 0, dexclient, true, payload); driven.transfer({value: 0, bounce:true, flag: 128, body:body}); } // Function for burn tokens by connector owner function burn(uint128 tokens, address callback_address, TvmCell callback_payload) public override { require(msg.sender == dexclient, 101); tvm.rawReserve(address(this).balance - msg.value, 2); TvmCell body = tvm.encodeBody(IBurnableByOwnerTokenWallet(driven).burnByOwner, tokens, 0, dexclient, callback_address, callback_payload); driven.transfer({value: 0, bounce:true, flag: 128, body:body}); } // Function for check balance function getBalance() public pure checkOwnerAndAccept returns (uint128 balance){ balance = address(this).balance; } // Function to receive plain transfers. receive() external { } }
Function to deployEmptyWallet
function deployEmptyWallet(address root) public override { require(msg.sender == dexclient, 101); require(msg.value >= GRAMS_TO_ROOT * 2, 103); tvm.rawReserve(address(this).balance - msg.value, 2); if (!statusConnected) { drivenRoot = root; TvmCell bodyD = tvm.encodeBody(IRootTokenContract(root).deployEmptyWallet, GRAMS_TO_NEW_WALLET, 0, address(this), dexclient); TvmCell bodyA = tvm.encodeBody(IRootTokenContract(root).sendExpectedWalletAddress, 0, address(this), address(this)); } }
12,832,567
[ 1, 2083, 358, 7286, 1921, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7286, 1921, 16936, 12, 2867, 1365, 13, 1071, 3849, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 302, 338, 2625, 16, 13822, 1769, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 15228, 2192, 55, 67, 4296, 67, 9185, 380, 576, 16, 1728, 23, 1769, 203, 565, 268, 3489, 18, 1899, 607, 6527, 12, 2867, 12, 2211, 2934, 12296, 300, 1234, 18, 1132, 16, 576, 1769, 203, 565, 309, 16051, 2327, 8932, 13, 288, 203, 1377, 5081, 837, 2375, 273, 1365, 31, 203, 1377, 399, 3489, 4020, 1417, 40, 273, 268, 3489, 18, 3015, 2250, 12, 45, 2375, 1345, 8924, 12, 3085, 2934, 12411, 1921, 16936, 16, 15228, 2192, 55, 67, 4296, 67, 12917, 67, 59, 1013, 15146, 16, 374, 16, 1758, 12, 2211, 3631, 302, 338, 2625, 1769, 203, 1377, 399, 3489, 4020, 1417, 37, 273, 268, 3489, 18, 3015, 2250, 12, 45, 2375, 1345, 8924, 12, 3085, 2934, 4661, 6861, 16936, 1887, 16, 374, 16, 1758, 12, 2211, 3631, 1758, 12, 2211, 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, -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; pragma experimental ABIEncoderV2; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ //CONTRACT HANDLING address contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false //AIRLINE HANDLING uint airlineId = 1; struct Airline{ address airline; uint id; bool status; bool paidFee; } mapping(address => Airline) private airlines; event AirlineAdded(address candidate, uint id, uint256 timestamp); event AirlineActive(address caller, uint256 valueSent, bool paid); //ELECTIONS HANDLING struct Vote{ address voter; uint voterNum; } //contains all votes for a specific candidate mapping(address => Vote[]) private elections; event VotePlacedFor(address candidate, uint id, uint256 timestamp); //FLIGHT HANDLING //flight ID uint flightId = 1; string[] flightList; struct Flight { string name; bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } //Flight availability check mapping(string => bool)flightAvailability; //Flights Info Statuses mapping(bytes32 => Flight) private flights; //Passenger Accounts by Flight mapping(address => mapping(string => uint256)) private passengerAccounts; //ADD MAPPING FLIGHT => PASSENGERS mapping(string => address[]) passengersOnFlight; //then take that array of addresses, and pay out to all of them using a loop event FlightRegistered(string flightName, uint flightId, address airline, uint8 statusCode, uint256 timestamp, bool flightAvailability); event InsurancePurchased(address passenger, string flightName, uint amount); event AccountsCredited(string flight, uint8 flightStatus); event WithdrawalMade(address payee, string flight, uint amount); /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor () public { contractOwner = msg.sender; airlines[contractOwner] = Airline({ airline: contractOwner, id: airlineId, status: true, paidFee: false }); emit AirlineAdded(contractOwner, airlines[contractOwner].id, block.timestamp); airlineId = airlineId.add(1); } /********************************************************************************************/ /* 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"); _; } //Requires registered airlines to have paid the registration fee //in order to participate in the contract modifier registryFeePaid(address caller){ require(airlines[caller].paidFee == true, "You must pay registration fee to do that"); _; } /********************************************************************************************/ /* 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 Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external { operational = mode; } //Returns owner of contract function getOwner() external view returns(address){ return contractOwner; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ //GET REGISTERED AIRLINE CALLER function verifyRegisteredAirline(address caller) view external requireIsOperational returns(bool){ if(airlines[caller].status == true){ return true; } } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { //check to see if candidate is already registered require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; //When there are less than 4 total registered airlines: if(airlineId <= 4){ //register airline airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); //increase airline ID number airlineId = airlineId.add(1); //emit 'Airline has been added' emit AirlineAdded(candidate, airlines[candidate].id, timestamp); //When there are 4 or more registered airlines: }else if(airlineId >= 5){ //Make sure candidate has not already been elected to the airlines registry require(airlines[candidate].status != true, "This candidate is already a registered airline"); //check to see if this voter has already voted for this candidate bool isDuplicate = false; for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); //get the 'electNum' from this particular candidate's mapping uint electNum; if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); }else{ electNum = 1; } //Get the number of votes that you need in order to elect candidate: // (50% of all registered airlines must vote for the candidate) uint totalRegistered = airlineId.sub(1); uint votesRequired = totalRegistered.mul(5).div(10); //Add vote to the candidate's election elections[candidate].push(Vote(voter, electNum)); //Once vote is made //if enough votes to elect have been reached if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); // emit "Airline has been added" emit AirlineAdded(candidate, airlines[candidate].id, timestamp); //increase global airlineId variable airlineId = airlineId.add(1); // else if msg.sender is not the final vote required to elect... }else{ //emit "Vote has been placed for..." emit VotePlacedFor(candidate, airlineId, timestamp); } } } //REGISTER FLIGHT function registerFlight(address airline, string flight) external registryFeePaid(airline){ uint256 savedTime = block.timestamp; bytes32 flightKey = getFlightKey(airline,flight, savedTime); flights[flightKey] = Flight(flight, true, 0, savedTime, airline); flightAvailability[flight] = true; //add flight to list flightList.push(flight); emit FlightRegistered(flight, flightId, airline, 0, flights[flightKey].updatedTimestamp, flightAvailability[flight]); flightId = flightId.add(1); } //GET FLIGHT LIST function getFlightList() external view returns(string[] memory){ return flightList; } /** * @dev Buy insurance for a flight * */ function buy(address passenger, string flight) external payable { require(flightAvailability[flight] == true, "Could not locate that flight"); require(msg.value > 0 ether, "You must send Ethers"); require(msg.value <= 1 ether, "Max amount is 1 ETH"); passengerAccounts[passenger][flight] = passengerAccounts[passenger][flight].add(msg.value); passengersOnFlight[flight].push(passenger); emit InsurancePurchased(passenger, flight, msg.value); } //PASSENGER CAN CHECK THEIR ACCOUNT BALANCE FOR A FLIGHT function getAccountBalance(address passenger, string flight) external view returns(uint256){ return passengerAccounts[passenger][flight]; } /** * @dev Credits payouts to insurees */ function creditInsurees(string flight, uint8 status) external { //require that the flight exists require(flightAvailability[flight]==true, "Could not locate that flight"); uint256 creditAmount; //check if flight is late, add credit to all those who hold //an account for that flight if(status >= 20 && status <= 50){ //loop through all account holders for the given flight for(uint a = 0; a < passengersOnFlight[flight].length; a++){ //passengersOnFlight[flight][a] //this equals an address //add credit to each of these accounts passengerAccounts[passengersOnFlight[flight][a]][flight] = passengerAccounts[passengersOnFlight[flight][a]][flight].mul(15).div(10); } emit AccountsCredited(flight, status); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address payee, string flight) external payable { //require that the caller (payee) has previously bought insurance require(passengerAccounts[payee][flight] > 0,"You do not have an account for this flight"); //payout amount uint256 payout = passengerAccounts[payee][flight]; //change account to 0 after ethers are paid out passengerAccounts[payee][flight] = 0; //send ethers to customer payee.transfer(payout); emit WithdrawalMade(payee, flight, payout); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address caller) external payable requireIsOperational { //if the caller of this function is registered, but has not paid their fee require(airlines[caller].paidFee != true, "You have already paid the registration fee"); require(msg.value >= 10 ether, "Please pay at least 10 ETH"); require(caller == tx.origin, "Contracts are not allowed"); uint256 cost = 10 ether; //changing statemachine ring addict bulb infant local year traffic candy wealth visual sand airlines[caller].paidFee = true; //state should be changed: bool collectAnswer = airlines[caller].paidFee; //return extra ethers caller.transfer(msg.value.sub(cost)); //emit event emit AirlineActive(caller, msg.value, collectAnswer); } 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. * */ function() external payable { //fund(); } }
CONTRACT HANDLINGAIRLINE HANDLING
contract FlightSuretyData { using SafeMath for uint; uint airlineId = 1; struct Airline{ address airline; uint id; bool status; bool paidFee; } mapping(address => Airline) private airlines; event AirlineAdded(address candidate, uint id, uint256 timestamp); event AirlineActive(address caller, uint256 valueSent, bool paid); struct Vote{ address voter; uint voterNum; } event VotePlacedFor(address candidate, uint id, uint256 timestamp); string[] flightList; mapping(address => Vote[]) private elections; uint flightId = 1; struct Flight { string name; bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } event FlightRegistered(string flightName, uint flightId, address airline, uint8 statusCode, uint256 timestamp, bool flightAvailability); event InsurancePurchased(address passenger, string flightName, uint amount); event AccountsCredited(string flight, uint8 flightStatus); event WithdrawalMade(address payee, string flight, uint amount); () public mapping(string => bool)flightAvailability; mapping(bytes32 => Flight) private flights; mapping(address => mapping(string => uint256)) private passengerAccounts; mapping(string => address[]) passengersOnFlight; constructor { contractOwner = msg.sender; airlines[contractOwner] = Airline({ airline: contractOwner, id: airlineId, status: true, paidFee: false }); emit AirlineAdded(contractOwner, airlines[contractOwner].id, block.timestamp); airlineId = airlineId.add(1); } { contractOwner = msg.sender; airlines[contractOwner] = Airline({ airline: contractOwner, id: airlineId, status: true, paidFee: false }); emit AirlineAdded(contractOwner, airlines[contractOwner].id, block.timestamp); airlineId = airlineId.add(1); } modifier requireIsOperational() { require(operational, "Contract is currently not operational"); } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier registryFeePaid(address caller){ require(airlines[caller].paidFee == true, "You must pay registration fee to do that"); _; } function isOperational() public view returns(bool) { return operational; } function setOperatingStatus ( bool mode ) external { operational = mode; } function getOwner() external view returns(address){ return contractOwner; } function verifyRegisteredAirline(address caller) view external requireIsOperational returns(bool){ if(airlines[caller].status == true){ return true; } } function verifyRegisteredAirline(address caller) view external requireIsOperational returns(bool){ if(airlines[caller].status == true){ return true; } } function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } airlineId = airlineId.add(1); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); }else if(airlineId >= 5){ require(airlines[candidate].status != true, "This candidate is already a registered airline"); bool isDuplicate = false; function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } uint electNum; function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } }else{ uint totalRegistered = airlineId.sub(1); elections[candidate].push(Vote(voter, electNum)); function registerAirline (address candidate, address voter) external registryFeePaid(voter) requireIsOperational { require(airlines[candidate].status != true, "This candidate is already a registered airline"); uint256 timestamp = now; if(airlineId <= 4){ airlines[candidate] = Airline({ airline: candidate, id: airlineId, status: true, paidFee: false }); for(uint a = 0; a < elections[candidate].length; a++){ if(elections[candidate][a].voter == voter){ isDuplicate = true; break; } } require(isDuplicate == false, "You have already voted for this candidate"); if(elections[candidate].length > 0){ electNum = elections[candidate].length.add(1); electNum = 1; } uint votesRequired = totalRegistered.mul(5).div(10); if(electNum >= votesRequired){ airlines[candidate] = Airline(candidate, airlineId, true, false); emit AirlineAdded(candidate, airlines[candidate].id, timestamp); airlineId = airlineId.add(1); emit VotePlacedFor(candidate, airlineId, timestamp); } } } }else{ function registerFlight(address airline, string flight) external registryFeePaid(airline){ uint256 savedTime = block.timestamp; bytes32 flightKey = getFlightKey(airline,flight, savedTime); flights[flightKey] = Flight(flight, true, 0, savedTime, airline); flightAvailability[flight] = true; flightList.push(flight); emit FlightRegistered(flight, flightId, airline, 0, flights[flightKey].updatedTimestamp, flightAvailability[flight]); flightId = flightId.add(1); } function getFlightList() external view returns(string[] memory){ return flightList; } function buy(address passenger, string flight) external payable { require(flightAvailability[flight] == true, "Could not locate that flight"); require(msg.value > 0 ether, "You must send Ethers"); require(msg.value <= 1 ether, "Max amount is 1 ETH"); passengerAccounts[passenger][flight] = passengerAccounts[passenger][flight].add(msg.value); passengersOnFlight[flight].push(passenger); emit InsurancePurchased(passenger, flight, msg.value); } function getAccountBalance(address passenger, string flight) external view returns(uint256){ return passengerAccounts[passenger][flight]; } function creditInsurees(string flight, uint8 status) external { require(flightAvailability[flight]==true, "Could not locate that flight"); uint256 creditAmount; if(status >= 20 && status <= 50){ for(uint a = 0; a < passengersOnFlight[flight].length; a++){ passengerAccounts[passengersOnFlight[flight][a]][flight] = passengerAccounts[passengersOnFlight[flight][a]][flight].mul(15).div(10); } emit AccountsCredited(flight, status); } } function creditInsurees(string flight, uint8 status) external { require(flightAvailability[flight]==true, "Could not locate that flight"); uint256 creditAmount; if(status >= 20 && status <= 50){ for(uint a = 0; a < passengersOnFlight[flight].length; a++){ passengerAccounts[passengersOnFlight[flight][a]][flight] = passengerAccounts[passengersOnFlight[flight][a]][flight].mul(15).div(10); } emit AccountsCredited(flight, status); } } function creditInsurees(string flight, uint8 status) external { require(flightAvailability[flight]==true, "Could not locate that flight"); uint256 creditAmount; if(status >= 20 && status <= 50){ for(uint a = 0; a < passengersOnFlight[flight].length; a++){ passengerAccounts[passengersOnFlight[flight][a]][flight] = passengerAccounts[passengersOnFlight[flight][a]][flight].mul(15).div(10); } emit AccountsCredited(flight, status); } } function pay(address payee, string flight) external payable { require(passengerAccounts[payee][flight] > 0,"You do not have an account for this flight"); uint256 payout = passengerAccounts[payee][flight]; passengerAccounts[payee][flight] = 0; payee.transfer(payout); emit WithdrawalMade(payee, flight, payout); } function fund(address caller) external payable requireIsOperational { require(airlines[caller].paidFee != true, "You have already paid the registration fee"); require(msg.value >= 10 ether, "Please pay at least 10 ETH"); require(caller == tx.origin, "Contracts are not allowed"); uint256 cost = 10 ether; airlines[caller].paidFee = true; bool collectAnswer = airlines[caller].paidFee; caller.transfer(msg.value.sub(cost)); emit AirlineActive(caller, msg.value, collectAnswer); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function() external payable { } }
14,033,734
[ 1, 6067, 2849, 1268, 24166, 26789, 37, 7937, 5997, 24166, 26789, 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, 16351, 3857, 750, 55, 594, 4098, 751, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 203, 377, 203, 203, 565, 2254, 23350, 1369, 548, 273, 404, 31, 203, 377, 203, 203, 565, 1958, 432, 481, 1369, 95, 203, 3639, 1758, 23350, 1369, 31, 203, 3639, 2254, 612, 31, 203, 3639, 1426, 1267, 31, 203, 3639, 1426, 30591, 14667, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 432, 481, 1369, 13, 3238, 23350, 3548, 31, 203, 203, 565, 871, 432, 481, 1369, 8602, 12, 2867, 5500, 16, 2254, 612, 16, 225, 2254, 5034, 2858, 1769, 203, 565, 871, 432, 481, 1369, 3896, 12, 2867, 4894, 16, 2254, 5034, 460, 7828, 16, 1426, 30591, 1769, 203, 203, 203, 565, 1958, 27540, 95, 203, 3639, 1758, 331, 20005, 31, 203, 3639, 2254, 331, 20005, 2578, 31, 203, 565, 289, 203, 203, 565, 871, 27540, 6029, 72, 1290, 12, 2867, 5500, 16, 2254, 612, 16, 2254, 5034, 2858, 1769, 203, 377, 203, 203, 203, 565, 533, 8526, 25187, 682, 31, 203, 203, 565, 2874, 12, 2867, 516, 27540, 63, 5717, 3238, 25526, 87, 31, 203, 203, 565, 2254, 25187, 548, 273, 404, 31, 203, 565, 1958, 3857, 750, 288, 203, 3639, 533, 508, 31, 203, 3639, 1426, 353, 10868, 31, 203, 3639, 2254, 28, 6593, 31, 203, 3639, 2254, 5034, 3526, 4921, 31, 540, 203, 3639, 1758, 23350, 1369, 31, 203, 565, 289, 203, 203, 565, 871, 3857, 750, 10868, 12, 1080, 25187, 461, 16, 2254, 25187, 548, 16, 1758, 23350, 1369, 2 ]
pragma solidity 0.4.19; /** * @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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { //Variables address public owner; address public newOwner; // Modifiers /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @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)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract SparkERC20 is StandardToken, Ownable { using SafeMath for uint256; /* Public variables of the token */ uint256 public creationBlock; uint8 public decimals; string public name; string public symbol; string public standard; bool public locked; /* Initializes contract with initial supply tokens to the creator of the contract */ function SparkERC20( uint256 _totalSupply, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transferAllSupplyToOwner, bool _locked ) public { standard = "ERC20 0.1"; locked = _locked; totalSupply = _totalSupply; if (_transferAllSupplyToOwner) { balances[msg.sender] = totalSupply; } else { balances[this] = totalSupply; } name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes creationBlock = block.number; } /* public methods */ function transfer(address _to, uint256 _value) public returns (bool) { require(locked == false); return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { if (locked) { return false; } return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { if (locked) { return false; } return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { if (locked) { return false; } return super.decreaseApproval(_spender, _subtractedValue); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (locked) { return false; } return super.transferFrom(_from, _to, _value); } } /* This contract manages the minters and the modifier to allow mint to happen only if called by minters This contract contains basic minting functionality though */ contract MintingERC20 is SparkERC20 { // Variables uint256 public maxSupply; mapping (address => bool) public minters; // Modifiers modifier onlyMinters() { require(true == minters[msg.sender]); _; } function MintingERC20( uint256 _initialSupply, uint256 _maxSupply, string _tokenName, uint8 _decimals, string _symbol, bool _transferAllSupplyToOwner, bool _locked ) public SparkERC20( _initialSupply, _tokenName, _decimals, _symbol, _transferAllSupplyToOwner, _locked ) { standard = "MintingERC20 0.1"; minters[msg.sender] = true; maxSupply = _maxSupply; } function addMinter(address _newMinter) public onlyOwner { minters[_newMinter] = true; } function removeMinter(address _minter) public onlyOwner { minters[_minter] = false; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (_amount == uint256(0)) { return uint256(0); } if (totalSupply.add(_amount) > maxSupply) { return uint256(0); } totalSupply = totalSupply.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(address(0), _addr, _amount); return _amount; } } contract Spark is MintingERC20 { ICO public ico; SparkDividends public dividends; bool public transferFrozen = true; function Spark( string _tokenName, uint8 _decimals, string _symbol, uint256 _maxSupply, bool _locked ) public MintingERC20(0, _maxSupply, _tokenName, _decimals, _symbol, false, _locked) { standard = "Spark 0.1"; } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = ICO(_ico); } function setSparkDividends(address _dividends) public onlyOwner { require(address(0) != _dividends); dividends = SparkDividends(_dividends); } function setLocked(bool _locked) public onlyOwner { locked = _locked; } // prevent manual minting tokens when ICO is active; function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { uint256 mintedAmount; if (msg.sender == owner) { require(address(ico) != address(0)); if (!ico.isActive() && block.timestamp >= ico.startTime()) { mintedAmount = super.mint(_addr, _amount); } } else { mintedAmount = super.mint(_addr, _amount); } if (mintedAmount == _amount) { require(address(dividends) != address(0)); dividends.logAccount(_addr, _amount); } return mintedAmount; } // Allow token transfer. function freezing(bool _transferFrozen) public onlyOwner { if (address(ico) != address(0) && !ico.isActive() && block.timestamp >= ico.startTime()) { transferFrozen = _transferFrozen; } } // ERC20 functions // ========================= function transfer(address _to, uint _value) public returns (bool) { require(!transferFrozen); bool status = super.transfer(_to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(msg.sender, 0); dividends.logAccount(_to, 0); } return status; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(!transferFrozen); bool status = super.transferFrom(_from, _to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(_from, 0); dividends.logAccount(_to, 0); } return status; } } contract WhiteList is Ownable { mapping (address => bool) public whitelist; /* events */ event WhitelistSet(address contributorAddress); event WhitelistUnset(address contributorAddress); modifier onlyWhitelisted() { require(true == whitelist[msg.sender]); _; } function WhiteList() public { whitelist[msg.sender] = true; } function addToWhitelist(address _address) public onlyOwner { whitelist[_address] = true; WhitelistSet(_address); } function removeFromWhitelist(address _address) public onlyOwner { whitelist[_address] = false; WhitelistUnset(_address); } } contract SparkDividends is Ownable { using SafeMath for uint256; Spark public spark; ICO public ico; address public treasuryAddress; mapping(address => DividendData[]) public accounts; FundsData[] public funds; struct DividendData { uint256 period; uint256 day; uint256 balance; } struct FundsData { uint256 period; uint256 ethersAmount; } event Disbursed(address indexed holder, uint256 value); modifier onlySparkContracts() { require(msg.sender == address(spark) || msg.sender == address(ico)); _; } function SparkDividends( address _spark, address _ico, address _treasuryAddress ) public { require(_spark != address(0) && _ico != address(0) && _treasuryAddress != address(0)); spark = Spark(_spark); ico = ICO(_ico); treasuryAddress = _treasuryAddress; } function setSpark(address _spark) public onlyOwner { require(_spark != address(0)); spark = Spark(_spark); } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = ICO(_ico); } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { require(_treasuryAddress != address(0)); treasuryAddress = _treasuryAddress; } function transferEthers() public onlyOwner { owner.transfer(this.balance); } function logAccount(address _address, uint256 _amount) public onlySparkContracts returns (bool) { uint256 day = 0; uint256 period = 1; if (now > ico.endTime()) { (period, day) = getPeriod(now); } if (_address != address(0) && period > 0) { if (day != 0 && _amount > 0) { logData(_address, period, 0, _amount); } logData(_address, period, day, 0); return true; } return false; } function setEtherAmount() public payable returns (bool) { if (msg.value == 0) { return false; } uint256 day = 0; uint256 period = 1; if (now > ico.endTime()) { (period, day) = getPeriod(now); } uint256 index = getFundsDataIndex(period); if (index == funds.length) { funds.push(FundsData(period, msg.value)); } else { funds[index].ethersAmount = funds[index].ethersAmount.add(msg.value); } return true; } function claim() public returns (bool) { uint256 currentDay; uint256 currentPeriod; bool status; (currentPeriod, currentDay) = getPeriod(now); if (currentPeriod == 1) { return false; } uint256 dividendAmount; uint256 outdatedAmount; (dividendAmount, outdatedAmount) = calculateAmount(msg.sender, currentPeriod, currentDay); if (dividendAmount == 0) { return false; } msg.sender.transfer(dividendAmount); if (outdatedAmount > 0) { treasuryAddress.transfer(outdatedAmount); } if (cleanDividendsData(msg.sender, currentPeriod)) { Disbursed(msg.sender, dividendAmount); status = true; } require(status); return true; } function calculateAmount( address _address, uint256 _currentPeriod, uint256 _currentDay ) public view returns (uint256 totalAmount, uint256 totalOutdated) { for (uint256 i = 0; i < accounts[_address].length; i++) { if (accounts[_address][i].period < _currentPeriod) { uint256 index = getFundsDataIndex(accounts[_address][i].period); if (index == funds.length) { continue; } uint256 dayEthers = funds[index].ethersAmount.div(90); uint256 balance; uint256 to = 90; if ( accounts[_address].length > i.add(1) && accounts[_address][i.add(1)].period == accounts[_address][i].period ) { to = accounts[_address][i.add(1)].day; } for (uint256 j = accounts[_address][i].day; j < to; j++) { balance = getBalanceByDay(_address, accounts[_address][i].period, j); if (_currentPeriod.sub(accounts[_address][i].period) > 1 && _currentDay > 2) { totalOutdated = totalOutdated.add(balance.mul(dayEthers).div(spark.maxSupply())); } else { totalAmount = totalAmount.add(balance.mul(dayEthers).div(spark.maxSupply())); } } } } } function logData(address _address, uint256 _period, uint256 _day, uint256 _amount) internal { uint256 index = getDividendDataIndex(_address, _period, _day); if (accounts[_address].length == index) { accounts[_address].push(DividendData(_period, _day, spark.balanceOf(_address).sub(_amount))); } else if (_amount == 0) { accounts[_address][index].balance = spark.balanceOf(_address); } } function getPeriod(uint256 _time) internal view returns (uint256, uint256) { uint256 day = uint(_time.sub(ico.endTime()) % 90 days).div(1 days); uint256 period = _time.sub(ico.endTime()).div(90 days); return (++period, day); } function cleanDividendsData(address _address, uint256 _currentPeriod) internal returns (bool) { for (uint256 i = 0; i < accounts[_address].length; i++) { if (accounts[_address][i].period < _currentPeriod) { for (uint256 j = i; j < accounts[_address].length.sub(1); j++) { DividendData storage dividend = accounts[_address][j]; dividend.period = accounts[_address][j.add(1)].period; dividend.day = accounts[_address][j.add(1)].day; dividend.balance = accounts[_address][j.add(1)].balance; } delete accounts[_address][accounts[_address].length.sub(1)]; accounts[_address].length--; i--; } } return true; } function getFundsDataIndex(uint256 _period) internal view returns (uint256) { for (uint256 i = 0; i < funds.length; i++) { if (funds[i].period == _period) { return i; } } return funds.length; } function getBalanceByDay(address _address, uint256 _period, uint256 _day) internal view returns (uint256) { for (uint256 i = accounts[_address].length.sub(1); i >= 0; i--) { if (accounts[_address][i].period == _period && accounts[_address][i].day <= _day) { return accounts[_address][i].balance; } } return 0; } function getDividendDataIndex(address _address, uint256 _period, uint256 _day) internal view returns (uint256) { for (uint256 i = 0; i < accounts[_address].length; i++) { if (accounts[_address][i].period == _period && accounts[_address][i].day == _day) { return i; } } return accounts[_address].length; } } contract Multivest is Ownable { /* public variables */ mapping (address => bool) public allowedMultivests; /* events */ event MultivestSet(address multivest); event MultivestUnset(address multivest); event Contribution(address holder, uint256 value, uint256 tokens); modifier onlyAllowedMultivests(address _addresss) { require(allowedMultivests[_addresss] == true); _; } /* constructor */ function Multivest(address _multivest) public { allowedMultivests[_multivest] = true; } function setAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = true; MultivestSet(_address); } function unsetAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = false; MultivestUnset(_address); } function multivestBuy(address _address, uint256 _value) public onlyAllowedMultivests(msg.sender) { require(buy(_address, _value) == true); } function multivestBuy( address _address, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyAllowedMultivests(verify(keccak256(msg.sender), _v, _r, _s)) { require(_address == msg.sender && buy(msg.sender, msg.value) == true); } function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns(address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; return ecrecover(keccak256(prefix, _hash), _v, _r, _s); } function buy(address _address, uint256 value) internal returns (bool); } contract SellableToken is Multivest { using SafeMath for uint256; // The token being sold Spark public spark; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // amount of sold tokens uint256 public soldTokens; // amount of raised money in wei uint256 public collectedEthers; // address where funds are collected address public etherHolder; address public tokensHolder; Bonus[] public bonuses; struct Bonus { uint256 maxAmount; uint256 bonus; } function SellableToken( address _multivestAddress, address _etherHolder, address _tokensHolder, address _spark, uint256 _startTime, uint256 _endTime ) public Multivest(_multivestAddress) { require(_spark != address(0) && _etherHolder != address(0) && _tokensHolder != address(0)); spark = Spark(_spark); etherHolder = _etherHolder; tokensHolder = _tokensHolder; require(_startTime < _endTime); startTime = _startTime; endTime = _endTime; } function setSpark(address _spark) public onlyOwner { require(_spark != address(0)); spark = Spark(_spark); } function setEtherHolder(address _etherHolder) public onlyOwner { require(_etherHolder != address(0)); etherHolder = _etherHolder; } function setTokenHolder(address _tokensHolder) public onlyOwner { require(_tokensHolder != address(0)); tokensHolder = _tokensHolder; } function transferEthers() public onlyOwner { etherHolder.transfer(this.balance); } // @return true if sale period is active function isActive() public constant returns (bool) { if (soldTokens == spark.maxSupply()) { return false; } return withinPeriod(); } // @return true if the transaction can buy tokens function withinPeriod() public constant returns (bool) { return block.timestamp >= startTime && block.timestamp <= endTime; } } contract ICO is SellableToken, WhiteList { uint256 public price; function ICO( address _multivestAddress, address _etherHolder, address _tokensHolder, address _spark, uint256 _startTime, uint256 _endTime, uint256 _price ) public SellableToken( _multivestAddress, _etherHolder, _tokensHolder, _spark, _startTime, _endTime ) WhiteList() { require(_price > 0); price = _price; bonuses.push(Bonus(uint(10000000).mul(uint(10) ** spark.decimals()), uint256(150))); bonuses.push(Bonus(uint(15000000).mul(uint(10) ** spark.decimals()), uint256(125))); bonuses.push(Bonus(uint(20000000).mul(uint(10) ** spark.decimals()), uint256(110))); } function() public payable onlyWhitelisted { require(buy(msg.sender, msg.value) == true); } function allocateUnsoldTokens() public { if (!isActive() && block.timestamp >= startTime) { uint256 amount = spark.maxSupply().sub(soldTokens); require(amount > 0 && spark.mint(tokensHolder, amount) == amount); soldTokens = spark.maxSupply(); } } function calculateTokensAmount(uint256 _value) public view returns (uint256 amount) { amount = _value.mul(uint(10) ** spark.decimals()).div(price); amount = amount.add(calculateBonusAmount(amount)); } function calculateEthersAmount(uint256 _tokens) public view returns (uint256 ethers, uint256 bonus) { if (_tokens == 0) { return (0, 0); } ethers = _tokens.mul(price).div(uint(10) ** spark.decimals()); bonus = calculateBonusAmount(_tokens); } function buy(address _address, uint256 _value) internal returns (bool) { if (_value == 0) { return false; } require(withinPeriod() && _address != address(0)); uint256 amount = calculateTokensAmount(_value); require(amount > 0 && spark.mint(_address, amount) == amount); collectedEthers = collectedEthers.add(_value); soldTokens = soldTokens.add(amount); Contribution(_address, _value, amount); return true; } function calculateBonusAmount(uint256 _amount) internal view returns (uint256) { uint256 newSoldTokens = soldTokens; uint256 remainingValue = _amount; for (uint i = 0; i < bonuses.length; i++) { if (bonuses[i].maxAmount > soldTokens) { uint256 amount = remainingValue.mul(bonuses[i].bonus).div(100); if (newSoldTokens.add(amount) > bonuses[i].maxAmount) { uint256 diff = bonuses[i].maxAmount.sub(newSoldTokens); remainingValue = remainingValue.sub(diff.mul(100).div(bonuses[i].bonus)); newSoldTokens = newSoldTokens.add(diff); } else { remainingValue = 0; newSoldTokens = newSoldTokens.add(amount); } if (remainingValue == 0) { break; } } } return newSoldTokens.add(remainingValue).sub(soldTokens.add(_amount)); } }
/ Variables Modifiers
contract MintingERC20 is SparkERC20 { uint256 public maxSupply; mapping (address => bool) public minters; This contract manages the minters and the modifier to allow mint to happen only if called by minters This contract contains basic minting functionality though modifier onlyMinters() { require(true == minters[msg.sender]); _; } function MintingERC20( uint256 _initialSupply, uint256 _maxSupply, string _tokenName, uint8 _decimals, string _symbol, bool _transferAllSupplyToOwner, bool _locked ) public SparkERC20( _initialSupply, _tokenName, _decimals, _symbol, _transferAllSupplyToOwner, _locked ) { standard = "MintingERC20 0.1"; minters[msg.sender] = true; maxSupply = _maxSupply; } function addMinter(address _newMinter) public onlyOwner { minters[_newMinter] = true; } function removeMinter(address _minter) public onlyOwner { minters[_minter] = false; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (_amount == uint256(0)) { return uint256(0); } if (totalSupply.add(_amount) > maxSupply) { return uint256(0); } totalSupply = totalSupply.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(address(0), _addr, _amount); return _amount; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (_amount == uint256(0)) { return uint256(0); } if (totalSupply.add(_amount) > maxSupply) { return uint256(0); } totalSupply = totalSupply.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(address(0), _addr, _amount); return _amount; } function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { if (_amount == uint256(0)) { return uint256(0); } if (totalSupply.add(_amount) > maxSupply) { return uint256(0); } totalSupply = totalSupply.add(_amount); balances[_addr] = balances[_addr].add(_amount); Transfer(address(0), _addr, _amount); return _amount; } }
5,464,414
[ 1, 19, 23536, 3431, 3383, 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, 490, 474, 310, 654, 39, 3462, 353, 21087, 654, 39, 3462, 288, 203, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 1131, 5432, 31, 203, 203, 2503, 6835, 20754, 281, 326, 1131, 5432, 471, 326, 9606, 358, 1699, 312, 474, 358, 5865, 1338, 309, 2566, 635, 1131, 5432, 203, 2503, 6835, 1914, 5337, 312, 474, 310, 14176, 11376, 203, 565, 9606, 1338, 49, 2761, 87, 1435, 288, 203, 3639, 2583, 12, 3767, 422, 1131, 5432, 63, 3576, 18, 15330, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 490, 474, 310, 654, 39, 3462, 12, 203, 3639, 2254, 5034, 389, 6769, 3088, 1283, 16, 203, 3639, 2254, 5034, 389, 1896, 3088, 1283, 16, 203, 3639, 533, 389, 2316, 461, 16, 203, 3639, 2254, 28, 389, 31734, 16, 203, 3639, 533, 389, 7175, 16, 203, 3639, 1426, 389, 13866, 1595, 3088, 1283, 774, 5541, 16, 203, 3639, 1426, 389, 15091, 203, 565, 262, 1071, 21087, 654, 39, 3462, 12, 203, 3639, 389, 6769, 3088, 1283, 16, 203, 3639, 389, 2316, 461, 16, 203, 3639, 389, 31734, 16, 203, 3639, 389, 7175, 16, 203, 3639, 389, 13866, 1595, 3088, 1283, 774, 5541, 16, 203, 3639, 389, 15091, 203, 565, 262, 203, 565, 288, 203, 3639, 4529, 273, 315, 49, 474, 310, 654, 39, 3462, 374, 18, 21, 14432, 203, 3639, 1131, 5432, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 943, 3088, 1283, 273, 389, 1896, 3088, 1283, 31, 2 ]
pragma solidity ^0.4.20; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract TokenERC20 { address public owner; // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; using SafeMath for uint256; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { owner = msg.sender; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } modifier onlyOwner { require(msg.sender == owner); _; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } function transfer(address _to, uint256 _value) public { require(!frozenAccount[msg.sender]); _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!frozenAccount[msg.sender]); require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) onlyOwner public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply =totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] =balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] =allowance[_from][msg.sender].sub(_value); // Subtract from the sender&#39;s allowance totalSupply =totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); transfer(_to, _value); require(_to.call(_data)); return true; } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); approve(_spender, _value); require(_spender.call(_data)); return true; } function transferOwnership(address _owner) onlyOwner public { owner = _owner; } function mintToken(address target, uint256 mintedAmount) public onlyOwner { balanceOf[target] =balanceOf[target].add(mintedAmount); totalSupply =totalSupply.add(mintedAmount); Transfer(0, owner, mintedAmount); Transfer(owner, target, mintedAmount); } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } }
Update totalSupply
totalSupply =totalSupply.sub(_value);
2,219,521
[ 1, 1891, 2078, 3088, 1283, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 273, 4963, 3088, 1283, 18, 1717, 24899, 1132, 1769, 1171, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x16f93D8CB09C04ebacD14F47C9d461643ed514c5/sources/contracts/Place.sol
* @dev Return value @return value of 'number'/
function retrieve() public view returns (uint8[64] memory){ return pixels; }
14,163,317
[ 1, 990, 460, 327, 460, 434, 296, 2696, 11, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4614, 1435, 1071, 1476, 1135, 261, 11890, 28, 63, 1105, 65, 3778, 15329, 203, 3639, 327, 8948, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SafeERC20} from "../../libs/SafeERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {MoneyMarket} from "../MoneyMarket.sol"; import {PRBMathUD60x18} from "prb-math/contracts/PRBMathUD60x18.sol"; import {IBToken} from "./imports/IBToken.sol"; import {IBComptroller} from "./imports/IBComptroller.sol"; contract BProtocolMarket is MoneyMarket { using PRBMathUD60x18 for uint256; using SafeERC20 for ERC20; using AddressUpgradeable for address; uint256 internal constant ERRCODE_OK = 0; IBToken public bToken; IBComptroller public bComptroller; address public rewards; ERC20 public override stablecoin; function initialize( address _bToken, address _bComptroller, address _rewards, address _rescuer, address _stablecoin ) external initializer { __MoneyMarket_init(_rescuer); // Verify input addresses require( _bToken.isContract() && _bComptroller.isContract() && _rewards != address(0) && _stablecoin.isContract(), "BProtocolMarket: Invalid input address" ); bToken = IBToken(_bToken); bComptroller = IBComptroller(_bComptroller); rewards = _rewards; stablecoin = ERC20(_stablecoin); } function deposit(uint256 amount) external override onlyOwner { require(amount > 0, "BProtocolMarket: amount is 0"); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Deposit `amount` stablecoin into bToken stablecoin.safeIncreaseAllowance(address(bToken), amount); require( bToken.mint(amount) == ERRCODE_OK, "BProtocolMarket: Failed to mint bTokens" ); } function withdraw(uint256 amountInUnderlying) external override onlyOwner returns (uint256 actualAmountWithdrawn) { require( amountInUnderlying > 0, "BProtocolMarket: amountInUnderlying is 0" ); // Withdraw `amountInUnderlying` stablecoin from bToken require( bToken.redeemUnderlying(amountInUnderlying) == ERRCODE_OK, "BProtocolMarket: Failed to redeem" ); // Transfer `amountInUnderlying` stablecoin to `msg.sender` stablecoin.safeTransfer(msg.sender, amountInUnderlying); return amountInUnderlying; } function claimRewards() external override { ERC20 comp = ERC20(bComptroller.registry().comp()); uint256 beforeBalance = comp.balanceOf(address(this)); bComptroller.claimComp(address(this)); comp.safeTransfer( rewards, comp.balanceOf(address(this)) - beforeBalance ); } /** Param setters */ function setRewards(address newValue) external override onlyOwner { require(newValue != address(0), "BProtocolMarket: 0 address"); rewards = newValue; emit ESetParamAddress(msg.sender, "rewards", newValue); } /** @dev IMPORTANT MUST READ This function is for restricting unauthorized accounts from taking funds and ensuring only tokens not used by the MoneyMarket can be rescued. IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST override it in a MoneyMarket implementation. 2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function. 3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued. 4) You SHOULD look at how existing MoneyMarkets do it as an example. */ function _authorizeRescue(address token, address target) internal view override { super._authorizeRescue(token, target); require(token != address(bToken), "BProtocolMarket: no steal"); } function _totalValue(uint256 currentIncomeIndex) internal view override returns (uint256) { uint256 bTokenBalance = bToken.balanceOf(address(this)); return bTokenBalance.mul(currentIncomeIndex); } function _incomeIndex() internal override returns (uint256 index) { index = bToken.exchangeRateCurrent(); require(index > 0, "BProtocolMarket: BAD_INDEX"); } uint256[46] private __gap; }
Verify input addresses
) external initializer { __MoneyMarket_init(_rescuer); require( _bToken.isContract() && _bComptroller.isContract() && _rewards != address(0) && _stablecoin.isContract(), "BProtocolMarket: Invalid input address" ); bToken = IBToken(_bToken); bComptroller = IBComptroller(_bComptroller); rewards = _rewards; stablecoin = ERC20(_stablecoin); }
12,738,485
[ 1, 8097, 810, 6138, 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, 262, 3903, 12562, 288, 203, 3639, 1001, 23091, 3882, 278, 67, 2738, 24899, 455, 71, 6211, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 389, 70, 1345, 18, 291, 8924, 1435, 597, 203, 7734, 389, 70, 799, 337, 1539, 18, 291, 8924, 1435, 597, 203, 7734, 389, 266, 6397, 480, 1758, 12, 20, 13, 597, 203, 7734, 389, 15021, 12645, 18, 291, 8924, 9334, 203, 5411, 315, 38, 5752, 3882, 278, 30, 1962, 810, 1758, 6, 203, 3639, 11272, 203, 203, 3639, 324, 1345, 273, 23450, 1345, 24899, 70, 1345, 1769, 203, 3639, 324, 799, 337, 1539, 273, 23450, 799, 337, 1539, 24899, 70, 799, 337, 1539, 1769, 203, 3639, 283, 6397, 273, 389, 266, 6397, 31, 203, 3639, 14114, 12645, 273, 4232, 39, 3462, 24899, 15021, 12645, 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 ]
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IExchange.sol"; import "./interfaces/ISortedOracles.sol"; import "./interfaces/IReserve.sol"; import "./interfaces/IStableToken.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/Freezable.sol"; import "../common/UsingRegistry.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title Contract that allows to exchange StableToken for GoldToken and vice versa * using a Constant Product Market Maker Model */ contract Exchange is IExchange, ICeloVersionedContract, Initializable, Ownable, UsingRegistry, ReentrancyGuard, Freezable { using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; event Exchanged(address indexed exchanger, uint256 sellAmount, uint256 buyAmount, bool soldGold); event UpdateFrequencySet(uint256 updateFrequency); event MinimumReportsSet(uint256 minimumReports); event StableTokenSet(address indexed stable); event SpreadSet(uint256 spread); event ReserveFractionSet(uint256 reserveFraction); event BucketsUpdated(uint256 goldBucket, uint256 stableBucket); FixidityLib.Fraction public spread; // Fraction of the Reserve that is committed to the gold bucket when updating // buckets. FixidityLib.Fraction public reserveFraction; address public stable; // Size of the Uniswap gold bucket uint256 public goldBucket; // Size of the Uniswap stable token bucket uint256 public stableBucket; uint256 public lastBucketUpdate = 0; uint256 public updateFrequency; uint256 public minimumReports; modifier updateBucketsIfNecessary() { _updateBucketsIfNecessary(); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 1, 0); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param stableToken Address of the stable token * @param _spread Spread charged on exchanges * @param _reserveFraction Fraction to commit to the gold bucket * @param _updateFrequency The time period that needs to elapse between bucket * updates * @param _minimumReports The minimum number of fresh reports that need to be * present in the oracle to update buckets * commit to the gold bucket */ function initialize( address registryAddress, address stableToken, uint256 _spread, uint256 _reserveFraction, uint256 _updateFrequency, uint256 _minimumReports ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setStableToken(stableToken); setSpread(_spread); setReserveFraction(_reserveFraction); setUpdateFrequency(_updateFrequency); setMinimumReports(_minimumReports); _updateBucketsIfNecessary(); } /** * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function sell(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) public onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 buyAmount = _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); require(buyAmount >= minBuyAmount, "Calculated buyAmount was less than specified minBuyAmount"); _exchange(sellAmount, buyAmount, sellGold); return buyAmount; } /** * @dev DEPRECATED - Use `buy` or `sell`. * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function exchange(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) external returns (uint256) { return sell(sellAmount, minBuyAmount, sellGold); } /** * @notice Exchanges an unspecified amount (up to a threshold) of one token for * a specific amount of another. * @param buyAmount The number of tokens for the exchange to send in return. * @param maxSellAmount The maximum number of tokens to send to the exchange. * @param buyGold True if the exchange is sending CELO to the caller, false otherwise. * @return The number of tokens sent to the exchange. * @dev The caller must first have approved `maxSellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function buy(uint256 buyAmount, uint256 maxSellAmount, bool buyGold) external onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { bool sellGold = !buyGold; (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 sellAmount = _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); require( sellAmount <= maxSellAmount, "Calculated sellAmount was greater than specified maxSellAmount" ); _exchange(sellAmount, buyAmount, sellGold); return sellAmount; } /** * @notice Exchanges a specific amount of one token for a specific amount of another. * @param sellAmount The number of tokens to send to the exchange. * @param buyAmount The number of tokens for the exchange to send in return. * @param sellGold True if the msg.sender is sending CELO to the exchange, false otherwise. */ function _exchange(uint256 sellAmount, uint256 buyAmount, bool sellGold) private { IReserve reserve = IReserve(registry.getAddressForOrDie(RESERVE_REGISTRY_ID)); if (sellGold) { goldBucket = goldBucket.add(sellAmount); stableBucket = stableBucket.sub(buyAmount); require( getGoldToken().transferFrom(msg.sender, address(reserve), sellAmount), "Transfer of sell token failed" ); require(IStableToken(stable).mint(msg.sender, buyAmount), "Mint of stable token failed"); } else { stableBucket = stableBucket.add(sellAmount); goldBucket = goldBucket.sub(buyAmount); require( IERC20(stable).transferFrom(msg.sender, address(this), sellAmount), "Transfer of sell token failed" ); IStableToken(stable).burn(sellAmount); require(reserve.transferExchangeGold(msg.sender, buyAmount), "Transfer of buyToken failed"); } emit Exchanged(msg.sender, sellAmount, buyAmount, sellGold); } /** * @notice Returns the amount of buy tokens a user would get for sellAmount of the sell token. * @param sellAmount The amount of sellToken the user is selling to the exchange. * @param sellGold `true` if gold is the sell token. * @return The corresponding buyToken amount. */ function getBuyTokenAmount(uint256 sellAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyAmount The amount of buyToken the user would like to purchase. * @param sellGold `true` if gold is the sell token. * @return The corresponding sellToken amount. */ function getSellTokenAmount(uint256 buyAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); } /** * @notice Returns the buy token and sell token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (buyTokenBucket, sellTokenBucket) */ function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); } else { return (currentGoldBucket, currentStableBucket); } } /** * @notice Allows owner to set the update frequency * @param newUpdateFrequency The new update frequency */ function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); } /** * @notice Allows owner to set the minimum number of reports required * @param newMininumReports The new update minimum number of reports required */ function setMinimumReports(uint256 newMininumReports) public onlyOwner { minimumReports = newMininumReports; emit MinimumReportsSet(newMininumReports); } /** * @notice Allows owner to set the Stable Token address * @param newStableToken The new address for Stable Token */ function setStableToken(address newStableToken) public onlyOwner { stable = newStableToken; emit StableTokenSet(newStableToken); } /** * @notice Allows owner to set the spread * @param newSpread The new value for the spread */ function setSpread(uint256 newSpread) public onlyOwner { spread = FixidityLib.wrap(newSpread); emit SpreadSet(newSpread); } /** * @notice Allows owner to set the Reserve Fraction * @param newReserveFraction The new value for the reserve fraction */ function setReserveFraction(uint256 newReserveFraction) public onlyOwner { reserveFraction = FixidityLib.wrap(newReserveFraction); require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1"); emit ReserveFractionSet(newReserveFraction); } /** * @notice Returns the sell token and buy token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (sellTokenBucket, buyTokenBucket) */ function _getBuyAndSellBuckets(bool sellGold) private view returns (uint256, uint256) { if (sellGold) { return (stableBucket, goldBucket); } else { return (goldBucket, stableBucket); } } /** * @dev Returns the amount of buy tokens a user would get for sellAmount of the sell. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param sellAmount The amount the user is selling to the exchange. * @return The corresponding buy amount. */ function _getBuyTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 sellAmount) private view returns (uint256) { if (sellAmount == 0) return 0; FixidityLib.Fraction memory reducedSellAmount = getReducedSellAmount(sellAmount); FixidityLib.Fraction memory numerator = reducedSellAmount.multiply( FixidityLib.newFixed(buyTokenBucket) ); FixidityLib.Fraction memory denominator = FixidityLib.newFixed(sellTokenBucket).add( reducedSellAmount ); // Can't use FixidityLib.divide because denominator can easily be greater // than maxFixedDivisor. // Fortunately, we expect an integer result, so integer division gives us as // much precision as we could hope for. return numerator.unwrap().div(denominator.unwrap()); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param buyAmount The amount the user is buying from the exchange. * @return The corresponding sell amount. */ function _getSellTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 buyAmount) private view returns (uint256) { if (buyAmount == 0) return 0; FixidityLib.Fraction memory numerator = FixidityLib.newFixed(buyAmount.mul(sellTokenBucket)); FixidityLib.Fraction memory denominator = FixidityLib .newFixed(buyTokenBucket.sub(buyAmount)) .multiply(FixidityLib.fixed1().subtract(spread)); // See comment in _getBuyTokenAmount return numerator.unwrap().div(denominator.unwrap()); } function getUpdatedBuckets() private view returns (uint256, uint256) { uint256 updatedGoldBucket = getUpdatedGoldBucket(); uint256 exchangeRateNumerator; uint256 exchangeRateDenominator; (exchangeRateNumerator, exchangeRateDenominator) = getOracleExchangeRate(); uint256 updatedStableBucket = exchangeRateNumerator.mul(updatedGoldBucket).div( exchangeRateDenominator ); return (updatedGoldBucket, updatedStableBucket); } function getUpdatedGoldBucket() private view returns (uint256) { uint256 reserveGoldBalance = getReserve().getUnfrozenReserveGoldBalance(); return reserveFraction.multiply(FixidityLib.newFixed(reserveGoldBalance)).fromFixed(); } /** * @notice If conditions are met, updates the Uniswap bucket sizes to track * the price reported by the Oracle. */ function _updateBucketsIfNecessary() private { if (shouldUpdateBuckets()) { // solhint-disable-next-line not-rely-on-time lastBucketUpdate = now; (goldBucket, stableBucket) = getUpdatedBuckets(); emit BucketsUpdated(goldBucket, stableBucket); } } /** * @notice Calculates the sell amount reduced by the spread. * @param sellAmount The original sell amount. * @return The reduced sell amount, computed as (1 - spread) * sellAmount */ function getReducedSellAmount(uint256 sellAmount) private view returns (FixidityLib.Fraction memory) { return FixidityLib.fixed1().subtract(spread).multiply(FixidityLib.newFixed(sellAmount)); } /* * @notice Checks conditions required for bucket updates. * @return Whether or not buckets should be updated. */ function shouldUpdateBuckets() private view returns (bool) { ISortedOracles sortedOracles = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ); (bool isReportExpired, ) = sortedOracles.isOldestReportExpired(stable); // solhint-disable-next-line not-rely-on-time bool timePassed = now >= lastBucketUpdate.add(updateFrequency); bool enoughReports = sortedOracles.numRates(stable) >= minimumReports; // solhint-disable-next-line not-rely-on-time bool medianReportRecent = sortedOracles.medianTimestamp(stable) > now.sub(updateFrequency); return timePassed && enoughReports && medianReportRecent && !isReportExpired; } function getOracleExchangeRate() private view returns (uint256, uint256) { uint256 rateNumerator; uint256 rateDenominator; (rateNumerator, rateDenominator) = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ) .medianRate(stable); require(rateDenominator > 0, "exchange rate denominator must be greater than 0"); return (rateNumerator, rateDenominator); } }
* @notice Allows owner to set the update frequency @param newUpdateFrequency The new update frequency/
function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); }
2,472,857
[ 1, 19132, 3410, 358, 444, 326, 1089, 8670, 225, 394, 1891, 13865, 1021, 394, 1089, 8670, 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, 225, 445, 444, 1891, 13865, 12, 11890, 5034, 394, 1891, 13865, 13, 1071, 1338, 5541, 288, 203, 565, 1089, 13865, 273, 394, 1891, 13865, 31, 203, 565, 3626, 2315, 13865, 694, 12, 2704, 1891, 13865, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 ton-solidity >= 0.35.0; pragma AbiHeader expire; interface Loaner { function borrow(uint128 amount) external; } // This contract implements 'Loaner' interface. contract LoanerContract is Loaner { // A function to be called from another contract // This function receives parameter 'amount' from another contract and // transfers 'amount' of currency to the caller. function borrow(uint128 amount) public override { // Before 'accept' here can be some checks (e.g: check that msg.sender is in while list) tvm.accept(); msg.sender.transfer(amount); } }
This contract implements 'Loaner' interface. A function to be called from another contract This function receives parameter 'amount' from another contract and transfers 'amount' of currency to the caller.
contract LoanerContract is Loaner { function borrow(uint128 amount) public override { tvm.accept(); msg.sender.transfer(amount); } }
15,817,333
[ 1, 2503, 6835, 4792, 296, 1504, 304, 264, 11, 1560, 18, 432, 445, 358, 506, 2566, 628, 4042, 6835, 1220, 445, 17024, 1569, 296, 8949, 11, 628, 4042, 6835, 471, 29375, 296, 8949, 11, 434, 5462, 358, 326, 4894, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 3176, 304, 264, 8924, 353, 3176, 304, 264, 288, 203, 203, 202, 915, 29759, 12, 11890, 10392, 3844, 13, 1071, 3849, 288, 203, 202, 202, 88, 3489, 18, 9436, 5621, 203, 203, 202, 202, 3576, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 202, 97, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-06-19 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.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 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); } } } } // // solhint-disable-next-line compiler-version /** * @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)); } } abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // /** * @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)); } } // /* * @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; } abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } 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; } // /** * @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); } // /** * @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; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // contract LiquidityPoolV3_02 is ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ERC20Upgradeable { using SafeMathUpgradeable for uint256; bytes32 constant public PAUSER_ROLE = keccak256("PAUSER_ROLE"); uint256 constant public N_TOKENS = 5; uint256 constant public NORM_BASE = 18; uint256 constant public CALC_PRECISION = 1e36; uint256 constant public PCT_PRECISION = 1e6; IERC20Upgradeable[N_TOKENS] public TOKENS; uint256[N_TOKENS] public TOKENS_MUL; uint256 public depositFee; uint256 public borrowFee; uint256 public adminFee; uint256 public adminBalance; address public adminFeeAddress; event SetFees(uint256 depositFee, uint256 borrowFee, uint256 adminFee); event SetAdminFeeAddress(address adminFeeAddress, address newAdminFeeAddress); event WithdrawAdminFee(address indexed addressTo, uint256[N_TOKENS] tokenAmounts, uint256 totalAmount); event Deposit(address indexed user, uint256[N_TOKENS] tokenAmounts, uint256 totalAmount, uint256 fee, uint256 mintedAmount); event Withdraw(address indexed user, uint256[N_TOKENS] tokenAmounts, uint256 burnedAmount); event Borrow(address indexed user, uint256[N_TOKENS] tokenAmounts, uint256 totalAmount, uint256 fee, uint256 adminFee); modifier onlyPauser() { require(hasRole(PAUSER_ROLE, msg.sender), "must have pauser role"); _; } function initialize( uint256 depositFee_, uint256 borrowFee_, uint256 adminFee_ ) public initializer { __ReentrancyGuard_init(); __AccessControl_init(); __Pausable_init_unchained(); __ERC20_init_unchained('HodlTree Flash Loans LP USD Token', 'hFLP-USD'); TOKENS = [ IERC20Upgradeable(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51), // sUSD IERC20Upgradeable(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd), // GUSD IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48), // USDC IERC20Upgradeable(0x6B175474E89094C44Da98b954EedeAC495271d0F), // DAI IERC20Upgradeable(0x0000000000085d4780B73119b644AE5ecd22b376) // TUSD ]; TOKENS_MUL = [ uint256(1), uint256(1e16), uint256(1e12), uint256(1), uint256(1) ]; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setRoleAdmin(PAUSER_ROLE, PAUSER_ROLE); setFees(depositFee_, borrowFee_, adminFee_); setAdminFeeAddress(msg.sender); } /*************************************** ADMIN ****************************************/ /** * @dev Sets new fees * @param depositFee_ deposit fee in ppm * @param borrowFee_ borrow fee in ppm * @param adminFee_ admin fee in ppm */ function setFees ( uint256 depositFee_, uint256 borrowFee_, uint256 adminFee_ ) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "must have admin role to set fees"); depositFee = depositFee_; borrowFee = borrowFee_; adminFee = adminFee_; emit SetFees(depositFee_, borrowFee_, adminFee_); } /** * @dev Sets admin fee address * @param newAdminFeeAddress_ new admin fee address */ function setAdminFeeAddress ( address newAdminFeeAddress_ ) public { require(newAdminFeeAddress_ != address(0), "admin fee address is zero"); require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "must have admin role to set admin fee address"); emit SetAdminFeeAddress(adminFeeAddress, newAdminFeeAddress_); adminFeeAddress = newAdminFeeAddress_; } /*************************************** PAUSER ****************************************/ /** * @dev Pause contract (disable deposit and borrow methods) */ function pause() external onlyPauser { _pause(); } /** * @dev Unause contract (enable deposit and borrow methods) */ function unpause() external onlyPauser { _unpause(); } /*************************************** PRIVATE ****************************************/ /** * @dev Calculates amount to mint internal tokens * @param amount_ normalised deposit amount * @param totalBalance_ normalised total balance of all tokens excluding admin fees * @param totalSupply_ internal token total supply * @return mintAmount_ amount to mint */ function _calcMint ( uint256 amount_, uint256 totalBalance_, uint256 totalSupply_ ) internal pure returns(uint256 mintAmount_) { mintAmount_ = amount_.mul( CALC_PRECISION ).div( totalBalance_ ).mul( totalSupply_ ).div( CALC_PRECISION ); } /** * @dev Returns normalised total balance of all tokens including admin fees * @return totalBalanceWithAdminFee_ balance */ function _totalBalanceWithAdminFee () internal view returns (uint256 totalBalanceWithAdminFee_) { for (uint256 i = 0; i < N_TOKENS; i++) { totalBalanceWithAdminFee_ = totalBalanceWithAdminFee_.add( (TOKENS[i].balanceOf(address(this))).mul(TOKENS_MUL[i]) ); } } /** * @dev Returns non-normalised token balances including admin fees * @return balancesWithAdminFee_ array of token balances */ function _balancesWithAdminFee () internal view returns (uint256[N_TOKENS] memory balancesWithAdminFee_) { for (uint256 i = 0; i < N_TOKENS; i++) { balancesWithAdminFee_[i] = TOKENS[i].balanceOf(address(this)); } } /** * @dev Withdraw tokens * @param amount_ amount of internal token to burn */ function _withdraw ( uint256 amount_, uint256[N_TOKENS] memory outAmounts_ ) internal { require(amount_ != 0, "withdraw amount is zero"); _burn(msg.sender, amount_); for (uint256 i = 0; i < N_TOKENS; i++) { if (outAmounts_[i] != 0) require(TOKENS[i].transfer(msg.sender, outAmounts_[i]), "token transfer failed"); } emit Withdraw(msg.sender, outAmounts_, amount_); } /*************************************** ACTIONS ****************************************/ function withdrawAdminFee () external nonReentrant returns (uint256[N_TOKENS] memory outAmounts_) { uint256 _adminBalance = adminBalance; require(_adminBalance != 0, "admin balance is zero"); uint256 _totalBalance = _totalBalanceWithAdminFee(); uint256[N_TOKENS] memory _balances = _balancesWithAdminFee(); for (uint256 i = 0; i < N_TOKENS; i++) { if(_balances[i] != 0){ outAmounts_[i] = _adminBalance.mul( CALC_PRECISION ).div( _totalBalance ).mul( _balances[i] ).div( CALC_PRECISION ); require(TOKENS[i].transfer(adminFeeAddress, outAmounts_[i])); } } emit WithdrawAdminFee(adminFeeAddress, outAmounts_, _adminBalance); adminBalance = 0; } /** * @dev Deposit tokens and mints internal tokens to sender as share in pool * @param amounts_ amounts of tokens to deposit in array */ function deposit ( uint256[N_TOKENS] calldata amounts_ ) external nonReentrant whenNotPaused returns (uint256 mintAmount_) { uint256 _totalAmount; uint256 _totalBalance = totalBalance(); for (uint256 i = 0; i < N_TOKENS; i++) { if (amounts_[i] != 0) { require( TOKENS[i].transferFrom(msg.sender, address(this), amounts_[i]), "token transfer failed" ); _totalAmount = _totalAmount.add(amounts_[i].mul(TOKENS_MUL[i])); } } require(_totalAmount != 0, "total deposit amount is zero"); uint256 _totalSupply = totalSupply(); uint256 _fee; if(_totalSupply != 0) { _fee = _totalAmount.mul(depositFee).div(PCT_PRECISION); mintAmount_ = _calcMint(_totalAmount.sub(_fee), _totalBalance, _totalSupply); }else{ mintAmount_ = _totalAmount; } _mint(msg.sender, mintAmount_); emit Deposit(msg.sender, amounts_, _totalAmount, _fee, mintAmount_); } /** * @dev Withdraw tokens in current pool proportion * @param amount_ amount of internal token to burn * @return outAmounts_ array of tokens amounts that were withdrawn */ function withdraw ( uint256 amount_ ) external nonReentrant returns (uint256[N_TOKENS] memory outAmounts_) { outAmounts_ = calcWithdraw(amount_); _withdraw(amount_, outAmounts_); } /** * @dev Withdraw tokens in unbalanced proportion * @param amount_ amount of internal token to burn * @param outAmountPCTs_ array of token amount percentages to withdraw * @return outAmounts_ array of tokens amounts that were withdrawn */ function widthdrawUnbalanced ( uint256 amount_, uint256[N_TOKENS] calldata outAmountPCTs_ ) external nonReentrant returns (uint256[N_TOKENS] memory outAmounts_) { outAmounts_ = calcWidthdrawUnbalanced(amount_, outAmountPCTs_); _withdraw(amount_, outAmounts_); } /** * @dev Withdraw exact tokens amounts * @param outAmounts_ array of token amount to withdraw * @return amount_ internal token amount burned on withdraw */ function widthdrawUnbalancedExactOut ( uint256[N_TOKENS] calldata outAmounts_ ) external nonReentrant returns (uint256 amount_) { amount_ = calcWidthdrawUnbalancedExactOut(outAmounts_); _withdraw(amount_, outAmounts_); } /** * @dev Flashloans tokens to caller * @param amounts_ array of token amounts to borrow * @param data_ encoded function callback to caller */ function borrow ( uint256[N_TOKENS] calldata amounts_, bytes calldata data_ ) external nonReentrant whenNotPaused { uint256 _totalAmount; uint256 _totalBalance; for (uint256 i = 0; i < N_TOKENS; i++) { _totalBalance = _totalBalance.add( (TOKENS[i].balanceOf(address(this))).mul(TOKENS_MUL[i]) ); if(amounts_[i] != 0) { _totalAmount = _totalAmount.add(amounts_[i].mul(TOKENS_MUL[i])); require(TOKENS[i].transfer(msg.sender, amounts_[i]), "token transfer failed"); } } require(_totalAmount != 0, "flashloan total amount is zero"); (bool _success, ) = address(msg.sender).call(data_); require(_success, "flashloan low-level callback failed"); uint256 _fee = calcBorrowFee(_totalAmount); require( _totalBalanceWithAdminFee() >= _totalBalance.add(_fee), "flashloan is not paid back as expected" ); uint256 _adminFee = _fee.mul(adminFee).div(PCT_PRECISION); adminBalance = adminBalance.add(_adminFee); emit Borrow(msg.sender, amounts_, _totalAmount, _fee.sub(_adminFee), _adminFee); } /*************************************** GETTERS ****************************************/ /** * @dev Returns normalised total balance of all tokens excluding admin fees * @return uint256 balance */ function totalBalance () public view returns (uint256) { return (_totalBalanceWithAdminFee()).sub(adminBalance); } /** * @dev Returns non-normalised token balances excluding admin fees * @return balances_ array of token balances */ function balances () public view returns (uint256[N_TOKENS] memory balances_) { uint256 _totalBalance = _totalBalanceWithAdminFee(); uint256[N_TOKENS] memory _balances = _balancesWithAdminFee(); for (uint256 i = 0; i < N_TOKENS; i++) { if(_balances[i] != 0){ balances_[i] = _balances[i].sub( adminBalance.mul( CALC_PRECISION ).div( _totalBalance ).mul( _balances[i] ).div( CALC_PRECISION ) ); } } } /** * @dev Returns non-normalised token balance excluding admin fees * @param token_ token index * @return uint256 token balance */ function balance (uint256 token_) public view returns (uint256) { return balances()[token_]; } /** * @dev Calculates withdraw amounts of tokens in current pool proportion * @param amount_ amount of internal token to burn * @return outAmounts_ array of token amounts will be returned on withdraw */ function calcWithdraw ( uint256 amount_ ) public view returns (uint256[N_TOKENS] memory outAmounts_) { uint256 _totalSupply = totalSupply(); uint256[N_TOKENS] memory _balances = balances(); for (uint256 i = 0; i < N_TOKENS; i++) { if (_balances[i] != 0) { outAmounts_[i] = amount_.mul( CALC_PRECISION ).div( _totalSupply ).mul( _balances[i] ).div( CALC_PRECISION ); } } } /** * @dev Calculates unbalanced withdraw tokens amounts * @param amount_ amount of internal token to burn * @param outAmountPCTs_ array of token amount percentages in ppm to withdraw * @return outAmounts_ array of token amounts will be returned on withdraw */ function calcWidthdrawUnbalanced ( uint256 amount_, uint256[N_TOKENS] calldata outAmountPCTs_ ) public view returns (uint256[N_TOKENS] memory outAmounts_) { uint256 _amount; uint256 _outAmountPCT; uint256 _totalSupply = totalSupply(); uint256 _totalBalance = totalBalance(); for (uint256 i = 0; i < N_TOKENS; i++) { if(outAmountPCTs_[i] != 0){ _amount = amount_.mul(outAmountPCTs_[i]).div(PCT_PRECISION); outAmounts_[i] = _amount.mul( CALC_PRECISION ).div( _totalSupply ).mul( _totalBalance.div(TOKENS_MUL[i]) ).div( CALC_PRECISION ); _outAmountPCT = _outAmountPCT.add(outAmountPCTs_[i]); } } require(_outAmountPCT == PCT_PRECISION, "total percentage is not 100% in ppm"); } /** * @dev Calculates internal token amount to butn for unbalanced withdraw with exact tokens amounts * @param outAmounts_ array of token amount to withdraw * @return amount_ internal token amount will be burned on withdraw */ function calcWidthdrawUnbalancedExactOut ( uint256[N_TOKENS] calldata outAmounts_ ) public view returns (uint256 amount_) { uint256 _totalSupply = totalSupply(); uint256 _totalBalance = totalBalance(); for (uint256 i = 0; i < N_TOKENS; i++) { if(outAmounts_[i] != 0){ amount_ = amount_.add( outAmounts_[i].mul( CALC_PRECISION ).div( _totalBalance.div(TOKENS_MUL[i]) ).mul( _totalSupply ).div( CALC_PRECISION ) ); } } } /** * @dev Calculates fee for flashloan * @param amount_ amount to borrow */ function calcBorrowFee ( uint256 amount_ ) public view returns (uint256) { return amount_.mul(borrowFee).div(PCT_PRECISION); } /** * @dev The current virtual price of internal pool token * @return uint256 normalised virtual price */ function virtualPrice () public view returns (uint256) { return (totalBalance()).mul(10 ** NORM_BASE).div(totalSupply()); } }
* @dev Deposit tokens and mints internal tokens to sender as share in pool @param amounts_ amounts of tokens to deposit in array/
function deposit ( uint256[N_TOKENS] calldata amounts_ ) external nonReentrant whenNotPaused returns (uint256 mintAmount_) { uint256 _totalAmount; uint256 _totalBalance = totalBalance(); for (uint256 i = 0; i < N_TOKENS; i++) { if (amounts_[i] != 0) { require( TOKENS[i].transferFrom(msg.sender, address(this), amounts_[i]), "token transfer failed" ); _totalAmount = _totalAmount.add(amounts_[i].mul(TOKENS_MUL[i])); } } require(_totalAmount != 0, "total deposit amount is zero"); uint256 _totalSupply = totalSupply(); uint256 _fee; if(_totalSupply != 0) { _fee = _totalAmount.mul(depositFee).div(PCT_PRECISION); mintAmount_ = _calcMint(_totalAmount.sub(_fee), _totalBalance, _totalSupply); mintAmount_ = _totalAmount; } _mint(msg.sender, mintAmount_); emit Deposit(msg.sender, amounts_, _totalAmount, _fee, mintAmount_); }
6,668,571
[ 1, 758, 1724, 2430, 471, 312, 28142, 2713, 2430, 358, 5793, 487, 7433, 316, 2845, 225, 30980, 67, 30980, 434, 2430, 358, 443, 1724, 316, 526, 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, 202, 915, 443, 1724, 261, 203, 202, 202, 11890, 5034, 63, 50, 67, 8412, 55, 65, 745, 892, 30980, 67, 203, 202, 13, 203, 202, 202, 9375, 203, 202, 202, 5836, 426, 8230, 970, 203, 202, 202, 13723, 1248, 28590, 203, 202, 202, 6154, 261, 11890, 5034, 312, 474, 6275, 67, 13, 203, 202, 95, 203, 202, 202, 11890, 5034, 389, 4963, 6275, 31, 203, 202, 202, 11890, 5034, 389, 4963, 13937, 273, 2078, 13937, 5621, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 423, 67, 8412, 55, 31, 277, 27245, 288, 203, 1082, 202, 430, 261, 8949, 87, 67, 63, 77, 65, 480, 374, 13, 288, 203, 9506, 202, 6528, 12, 203, 6862, 202, 8412, 55, 63, 77, 8009, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 30980, 67, 63, 77, 65, 3631, 203, 6862, 202, 6, 2316, 7412, 2535, 6, 203, 9506, 202, 1769, 203, 9506, 202, 67, 4963, 6275, 273, 389, 4963, 6275, 18, 1289, 12, 8949, 87, 67, 63, 77, 8009, 16411, 12, 8412, 55, 67, 49, 1506, 63, 77, 5717, 1769, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 202, 6528, 24899, 4963, 6275, 480, 374, 16, 315, 4963, 443, 1724, 3844, 353, 3634, 8863, 203, 202, 202, 11890, 5034, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 202, 202, 11890, 5034, 389, 21386, 31, 203, 202, 202, 430, 24899, 4963, 3088, 1283, 480, 374, 13, 288, 203, 1082, 202, 67, 21386, 273, 389, 4963, 6275, 18, 2 ]
pragma solidity ^0.8.0; import "../token/FeiTimedMinter.sol"; import "../oracle/collateralization/ICollateralizationOracleWrapper.sol"; /// @title CollateralizationOracleKeeper /// @notice a FEI timed minter which only rewards when updating the collateralization oracle contract CollateralizationOracleKeeper is FeiTimedMinter { ICollateralizationOracleWrapper public collateralizationOracleWrapper; /** @notice constructor for CollateralizationOracleKeeper @param _core the Core address to reference @param _incentive the incentive amount for calling mint paid in FEI @param _collateralizationOracleWrapper the collateralizationOracleWrapper to incentivize updates only sets the target to this address and mint amount to 0, relying exclusively on the incentive payment to caller */ constructor( address _core, uint256 _incentive, ICollateralizationOracleWrapper _collateralizationOracleWrapper ) FeiTimedMinter(_core, address(this), _incentive, MIN_MINT_FREQUENCY, 0) { collateralizationOracleWrapper = _collateralizationOracleWrapper; } function _afterMint() internal override { collateralizationOracleWrapper.updateIfOutdated(); } } pragma solidity ^0.8.0; import "../refs/CoreRef.sol"; import "../utils/Timed.sol"; import "../utils/Incentivized.sol"; import "../utils/RateLimitedMinter.sol"; import "./IFeiTimedMinter.sol"; /// @title FeiTimedMinter /// @notice a contract which mints FEI to a target address on a timed cadence contract FeiTimedMinter is IFeiTimedMinter, CoreRef, Timed, Incentivized, RateLimitedMinter { /// @notice most frequent that mints can happen uint256 public constant override MIN_MINT_FREQUENCY = 1 hours; // Min 1 hour per mint /// @notice least frequent that mints can happen uint256 public constant override MAX_MINT_FREQUENCY = 30 days; // Max 1 month per mint uint256 private _mintAmount; /// @notice the target receiving minted FEI address public override target; /** @notice constructor for FeiTimedMinter @param _core the Core address to reference @param _target the target for minted FEI @param _incentive the incentive amount for calling mint paid in FEI @param _frequency the frequency minting happens @param _initialMintAmount the initial FEI amount to mint */ constructor( address _core, address _target, uint256 _incentive, uint256 _frequency, uint256 _initialMintAmount ) CoreRef(_core) Timed(_frequency) Incentivized(_incentive) RateLimitedMinter((_initialMintAmount + _incentive) / _frequency, (_initialMintAmount + _incentive), true) { _initTimed(); _setTarget(_target); _setMintAmount(_initialMintAmount); } /// @notice triggers a minting of FEI /// @dev timed and incentivized function mint() public virtual override whenNotPaused afterTime { /// Reset the timer _initTimed(); uint256 amount = mintAmount(); // incentivizing before minting so if there is a partial mint it goes to target not caller _incentivize(); if (amount != 0) { // Calls the overriden RateLimitedMinter _mintFei which includes the rate limiting logic _mintFei(target, amount); emit FeiMinting(msg.sender, amount); } // After mint called whether a "mint" happens or not to allow incentivized target hooks _afterMint(); } function mintAmount() public view virtual override returns (uint256) { return _mintAmount; } /// @notice set the new FEI target function setTarget(address newTarget) external override onlyGovernor { _setTarget(newTarget); } /// @notice set the mint frequency function setFrequency(uint256 newFrequency) external override onlyGovernorOrAdmin { require(newFrequency >= MIN_MINT_FREQUENCY, "FeiTimedMinter: frequency low"); require(newFrequency <= MAX_MINT_FREQUENCY, "FeiTimedMinter: frequency high"); _setDuration(newFrequency); } function setMintAmount(uint256 newMintAmount) external override onlyGovernorOrAdmin { _setMintAmount(newMintAmount); } function _setTarget(address newTarget) internal { require(newTarget != address(0), "FeiTimedMinter: zero address"); address oldTarget = target; target = newTarget; emit TargetUpdate(oldTarget, newTarget); } function _setMintAmount(uint256 newMintAmount) internal { uint256 oldMintAmount = _mintAmount; _mintAmount = newMintAmount; emit MintAmountUpdate(oldMintAmount, newMintAmount); } function _mintFei(address to, uint256 amountIn) internal override(CoreRef, RateLimitedMinter) { RateLimitedMinter._mintFei(to, amountIn); } function _afterMint() internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; /// @notice boolean to check whether or not the contract has been initialized. /// cannot be initialized twice. bool private _initialized; constructor(address coreAddress) { _initialize(coreAddress); } /// @notice CoreRef constructor /// @param coreAddress Fei Core to reference function _initialize(address coreAddress) internal { require(!_initialized, "CoreRef: already initialized"); _initialized = true; _core = ICore(coreAddress); _setContractAdminRole(_core.GOVERN_ROLE()); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } /// @notice set new Core reference address /// @param newCore the new core address function setCore(address newCore) external override onlyGovernor { require(newCore != address(0), "CoreRef: zero address"); address oldCore = address(_core); _core = ICore(newCore); emit CoreUpdate(oldCore, newCore); } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { fei().mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setCore(address newCore) external; function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../token/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title an abstract contract for timed events /// @author Fei Protocol abstract contract Timed { /// @notice the start timestamp of the timed period uint256 public startTime; /// @notice the duration of the timed period uint256 public duration; event DurationUpdate(uint256 oldDuration, uint256 newDuration); event TimerReset(uint256 startTime); constructor(uint256 _duration) { _setDuration(_duration); } modifier duringTime() { require(isTimeStarted(), "Timed: time not started"); require(!isTimeEnded(), "Timed: time ended"); _; } modifier afterTime() { require(isTimeEnded(), "Timed: time not ended"); _; } /// @notice return true if time period has ended function isTimeEnded() public view returns (bool) { return remainingTime() == 0; } /// @notice number of seconds remaining until time is up /// @return remaining function remainingTime() public view returns (uint256) { return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d] } /// @notice number of seconds since contract was initialized /// @return timestamp /// @dev will be less than or equal to duration function timeSinceStart() public view returns (uint256) { if (!isTimeStarted()) { return 0; // uninitialized } uint256 _duration = duration; uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime return timePassed > _duration ? _duration : timePassed; } function isTimeStarted() public view returns (bool) { return startTime != 0; } function _initTimed() internal { startTime = block.timestamp; emit TimerReset(block.timestamp); } function _setDuration(uint256 newDuration) internal { require(newDuration != 0, "Timed: zero duration"); uint256 oldDuration = duration; duration = newDuration; emit DurationUpdate(oldDuration, newDuration); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; /// @title abstract contract for incentivizing keepers /// @author Fei Protocol abstract contract Incentivized is CoreRef { /// @notice FEI incentive for calling keeper functions uint256 public incentiveAmount; event IncentiveUpdate(uint256 oldIncentiveAmount, uint256 newIncentiveAmount); constructor(uint256 _incentiveAmount) { incentiveAmount = _incentiveAmount; emit IncentiveUpdate(0, _incentiveAmount); } /// @notice set the incentiveAmount function setIncentiveAmount(uint256 newIncentiveAmount) public onlyGovernor { uint256 oldIncentiveAmount = incentiveAmount; incentiveAmount = newIncentiveAmount; emit IncentiveUpdate(oldIncentiveAmount, newIncentiveAmount); } /// @notice incentivize a call with incentiveAmount FEI rewards /// @dev no-op if the contract does not have Minter role function _incentivize() internal ifMinterSelf { _mintFei(msg.sender, incentiveAmount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./RateLimited.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can mint FEI /// @author Fei Protocol abstract contract RateLimitedMinter is RateLimited { uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day constructor( uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, bool _doPartialMint ) RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint) {} /// @notice override the FEI minting behavior to enforce a rate limit function _mintFei(address to, uint256 amount) internal virtual override { uint256 mintAmount = _depleteBuffer(amount); super._mintFei(to, mintAmount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting /// @author Fei Protocol abstract contract RateLimited is CoreRef { /// @notice maximum rate limit per second governance can set for this contract uint256 public immutable MAX_RATE_LIMIT_PER_SECOND; /// @notice the rate per second for this contract uint256 public rateLimitPerSecond; /// @notice the last time the buffer was used by the contract uint256 public lastBufferUsedTime; /// @notice the cap of the buffer that can be used at once uint256 public bufferCap; /// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount bool public doPartialAction; /// @notice the buffer at the timestamp of lastBufferUsedTime uint256 private _bufferStored; event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap); event RateLimitPerSecondUpdate(uint256 oldRateLimitPerSecond, uint256 newRateLimitPerSecond); constructor(uint256 _maxRateLimitPerSecond, uint256 _rateLimitPerSecond, uint256 _bufferCap, bool _doPartialAction) { lastBufferUsedTime = block.timestamp; _bufferStored = _bufferCap; _setBufferCap(_bufferCap); require(_rateLimitPerSecond <= _maxRateLimitPerSecond, "RateLimited: rateLimitPerSecond too high"); _setRateLimitPerSecond(_rateLimitPerSecond); MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond; doPartialAction = _doPartialAction; } /// @notice set the rate limit per second function setRateLimitPerSecond(uint256 newRateLimitPerSecond) external onlyGovernorOrAdmin { require(newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND, "RateLimited: rateLimitPerSecond too high"); _setRateLimitPerSecond(newRateLimitPerSecond); } /// @notice set the buffer cap function setbufferCap(uint256 newBufferCap) external onlyGovernorOrAdmin { _setBufferCap(newBufferCap); } /// @notice the amount of action used before hitting limit /// @dev replenishes at rateLimitPerSecond per second up to bufferCap function buffer() public view returns(uint256) { uint256 elapsed = block.timestamp - lastBufferUsedTime; return Math.min(_bufferStored + (rateLimitPerSecond * elapsed), bufferCap); } /** @notice the method that enforces the rate limit. Decreases buffer by "amount". If buffer is <= amount either 1. Does a partial mint by the amount remaining in the buffer or 2. Reverts Depending on whether doPartialAction is true or false */ function _depleteBuffer(uint256 amount) internal returns(uint256) { uint256 newBuffer = buffer(); uint256 usedAmount = amount; if (doPartialAction && usedAmount > newBuffer) { usedAmount = newBuffer; } require(newBuffer != 0, "RateLimited: no rate limit buffer"); require(usedAmount <= newBuffer, "RateLimited: rate limit hit"); _bufferStored = newBuffer - usedAmount; lastBufferUsedTime = block.timestamp; return usedAmount; } function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal { // Reset the stored buffer and last buffer used time using the prior RateLimitPerSecond _bufferStored = buffer(); lastBufferUsedTime = block.timestamp; uint256 oldRateLimitPerSecond = rateLimitPerSecond; rateLimitPerSecond = newRateLimitPerSecond; emit RateLimitPerSecondUpdate(oldRateLimitPerSecond, newRateLimitPerSecond); } function _setBufferCap(uint256 newBufferCap) internal { uint256 oldBufferCap = bufferCap; bufferCap = newBufferCap; // Cap the existing stored buffer if (_bufferStored > newBufferCap) { _bufferStored = newBufferCap; } emit BufferCapUpdate(oldBufferCap, newBufferCap); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title a Fei Timed Minter /// @author Fei Protocol interface IFeiTimedMinter { // ----------- Events ----------- event FeiMinting(address indexed caller, uint256 feiAmount); event TargetUpdate(address oldTarget, address newTarget); event MintAmountUpdate(uint256 oldMintAmount, uint256 newMintAmount); // ----------- State changing api ----------- function mint() external; // ----------- Governor only state changing api ----------- function setTarget(address newTarget) external; // ----------- Governor or Admin only state changing api ----------- function setFrequency(uint256 newFrequency) external; function setMintAmount(uint256 newMintAmount) external; // ----------- Getters ----------- function mintAmount() external view returns(uint256); function MIN_MINT_FREQUENCY() external view returns(uint256); function MAX_MINT_FREQUENCY() external view returns(uint256); function target() external view returns(address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICollateralizationOracle.sol"; /// @title Collateralization ratio oracle interface for Fei Protocol /// @author Fei Protocol interface ICollateralizationOracleWrapper is ICollateralizationOracle { // ----------- Events ------------------------------------------------------ event CachedValueUpdate( address from, uint256 indexed protocolControlledValue, uint256 indexed userCirculatingFei, int256 indexed protocolEquity ); event CollateralizationOracleUpdate( address from, address indexed oldOracleAddress, address indexed newOracleAddress ); event DeviationThresholdUpdate( address from, uint256 indexed oldThreshold, uint256 indexed newThreshold ); event ReadPauseOverrideUpdate( bool readPauseOverride ); // ----------- Public state changing api ----------- function updateIfOutdated() external; // ----------- Governor only state changing api ----------- function setValidityDuration(uint256 _validityDuration) external; function setReadPauseOverride(bool newReadPauseOverride) external; function setDeviationThresholdBasisPoints(uint256 _newDeviationThresholdBasisPoints) external; function setCollateralizationOracle(address _newCollateralizationOracle) external; function setCache( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity ) external; // ----------- Getters ----------- function cachedProtocolControlledValue() external view returns (uint256); function cachedUserCirculatingFei() external view returns (uint256); function cachedProtocolEquity() external view returns (int256); function deviationThresholdBasisPoints() external view returns (uint256); function collateralizationOracle() external view returns(address); function isOutdatedOrExceededDeviationThreshold() external view returns (bool); function pcvStatsCurrent() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); function isExceededDeviationThreshold() external view returns (bool); function readPauseOverride() external view returns(bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../IOracle.sol"; /// @title Collateralization ratio oracle interface for Fei Protocol /// @author Fei Protocol interface ICollateralizationOracle is IOracle { // ----------- Getters ----------- // returns the PCV value, User-circulating FEI, and Protocol Equity, as well // as a validity status. function pcvStats() external view returns ( uint256 protocolControlledValue, uint256 userCirculatingFei, int256 protocolEquity, bool validityStatus ); // true if Protocol Equity > 0 function isOvercollateralized() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
@notice return true if time period has ended
function isTimeEnded() public view returns (bool) { return remainingTime() == 0; }
936,174
[ 1, 2463, 638, 309, 813, 3879, 711, 16926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 353, 950, 28362, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 4463, 950, 1435, 422, 374, 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 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./GovernanceManager.sol"; import "./GovernanceMaxLock.sol"; import "./GovernanceProposal.sol"; import "./GovernanceStorage.sol"; import "./Governance.sol"; import "./StakeNFT.sol"; import "./interfaces/INFTStake.sol"; import "./lib/openzeppelin/token/ERC20/ERC20.sol"; uint256 constant ONE_MADTOKEN = 10**18; contract MadTokenMock is ERC20 { constructor(address to_) ERC20("MadToken", "MAD") { _mint(to_, 220000000 * ONE_MADTOKEN); } } contract MinerStake is INFTStake { StakeNFT stakeNFT; constructor(StakeNFT stakeNFT_) { stakeNFT = stakeNFT_; } function lockPosition(address caller_, uint256 tokenID_, uint256 lockDuration_) external override returns(uint256 numberShares) { return stakeNFT.lockPosition(caller_, tokenID_, lockDuration_); } function mintTo(address to_, uint256 amount_, uint256 lockDuration_) public returns(uint256 tokenID) { return stakeNFT.mintTo(to_, amount_, lockDuration_); } } contract MockGovernanceOnlyAction is Governance, DSTest { constructor(address _governance) Governance(address(_governance)) {} function dummy() public onlyGovernance returns(bool){ emit log("Oh god, I got executed!"); emit log_named_address("Dummy: msg.sender in the dummy", msg.sender); return true; } } contract MockProposalLogic is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { emit log_named_address("msg.sender", msg.sender); address _logic = 0x3A1148FE01e3c4721D93fe8A36c2b5C29109B6ae; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummy()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return true; } } contract MockProposalLogicFailedLogic is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { revert("Proposal with failed logic!"); } } contract MockProposalChangeGovernanceManagerStorage is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { _votemap[1][address(_Stake)][1]=false; _MinerStake=INFTStake(address(0x0)); _proposals[1] = GovernanceStorage.Proposal(false, address(0x0), 0, 666); _threshold=1; } } contract MockProposalLogicWithAllowedProposals is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { emit log_named_address("MockProposalLogicWithAllowedProposals: msg.sender", msg.sender); // Address of the deployed MockProposalLogicWithOutAllowedProposals // contract. This contract is a middle man that doesn't have governance // powers. See the contract bellow. address _logic = 0xbfFb01bB2DDb4EfA87cB78EeCB8115AFAe6d2032; // giving the _logic address governance powers to call governance methods allowedProposal = _logic; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummyNoDelegate()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract MockProposalLogicWithOutAllowedProposals is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { emit log_named_address("MockProposalLogicWithAllowedProposals: msg.sender", msg.sender); address _logic = 0xbfFb01bB2DDb4EfA87cB78EeCB8115AFAe6d2032; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummyNoDelegate()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract NoGovernanceDelegateCall is DSTest { function dummyNoDelegate() public returns (bool){ emit log_named_address("NoGovernanceDelegateCall: msg.sender", msg.sender); address _logic = 0x3A1148FE01e3c4721D93fe8A36c2b5C29109B6ae; (bool success, bytes memory data) = _logic.call(abi.encodeWithSignature("dummy()")); require(success, "GovernanceManager: CALL FAILED to execute proposal"); emit log_named_bytes("Executed successful", data); return success; } } contract MockProposalChangeGovernanceManagerStorageStake is GovernanceProposal, DSTest { function execute(address self) public override virtual returns(bool) { return _execute(); } function _execute() internal virtual returns(bool) { _Stake=INFTStake(address(0x0)); } } abstract contract BaseMock { StakeNFT public stakeNFT; MadTokenMock public madToken; GovernanceManager public governanceManager; function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; } receive() external payable virtual {} } contract AdminAccount is BaseMock { constructor() {} function tripCB() public { stakeNFT.tripCB(); } function setTokens(MadTokenMock madToken_, StakeNFT stakeNFT_, GovernanceManager governanceManager_) public override virtual { stakeNFT = stakeNFT_; madToken = madToken_; governanceManager = governanceManager_; setGovernance(address(governanceManager_)); } function setGovernance(address governance_) public { stakeNFT.setGovernance(governance_); } } contract UserAccount is BaseMock { constructor() {} function voteAsMiner(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsMiner(proposalID_, tokenID_); } function voteAsStaker(uint256 proposalID_, uint256 tokenID_) public { governanceManager.voteAsStaker(proposalID_, tokenID_); } } contract GovernanceManagerTest is DSTest { function getFixtureData() internal returns ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) { admin = new AdminAccount(); AdminAccount adminMiner = new AdminAccount(); madToken = new MadTokenMock(address(this)); stakeNFT = new StakeNFT( IERC20Transfer(address(madToken)), address(admin), address(address(0x0)) ); minerStake = MinerStake(address (new StakeNFT( IERC20Transfer(address(madToken)), address(adminMiner), address(address(0x0)) ))); governanceManager = new GovernanceManager(address(stakeNFT), address(minerStake)); admin.setTokens(madToken, stakeNFT, governanceManager); adminMiner.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function newUserAccount(MadTokenMock madToken, StakeNFT stakeNFT, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, stakeNFT, governanceManager); } function newUserAccount(MadTokenMock madToken, MinerStake minerStake, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function setBlockNumber(uint256 bn) internal returns (bool) { // https://github.com/dapphub/dapptools/tree/master/src/hevm#cheat-codes address externalContract = address( 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D ); (bool success, /*bytes memory returnedData*/) = externalContract.call( abi.encodeWithSignature("roll(uint256)", bn) ); return success; } function assertProposal(GovernanceStorage.Proposal memory actual, GovernanceStorage.Proposal memory expected) public { assertTrue(actual.executed == expected.executed); assertEq(actual.logic, expected.logic); assertEq(actual.voteCount, expected.voteCount); assertEq(actual.blockEndVote, expected.blockEndVote); } function test_CreateProposal() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); } function testFail_CreateProposalWithLogicAddressZero() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); uint256 proposalID = governanceManager.propose(address(0x0)); } function testVoteAsStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } } function testVoteAsMiner() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, minerStake, governanceManager); madToken.approve(address(minerStake), 11_220_000 * 10**18); uint256 tokenID = minerStake.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsMiner(proposalID, tokenID); } } function testSameUserVotesAsMinerAndStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); UserAccount[10] memory users; madToken.approve(address(minerStake), 110_000_000 * 10**18); madToken.approve(address(stakeNFT), 110_000_000 * 10**18); for (uint256 i =0; i < 10; i++){ users[i] = newUserAccount(madToken, minerStake, governanceManager); uint256 minerTokenId = minerStake.mintTo(address(users[i]), 11_000_000 * 10**18, 1); emit log_named_uint("miner token", minerTokenId); uint256 stakeTokenId = stakeNFT.mintTo(address(users[i]), 11_000_000 * 10**18, 1); emit log_named_uint("stake token", stakeTokenId); assertEq(minerTokenId, stakeTokenId); } for (uint256 i =0; i < 10; i++){ users[i].voteAsMiner(proposalID, i+1); users[i].voteAsStaker(proposalID, i+1); } } function testFail_TryToVoteNonExistingProposalId() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); governanceManager.voteAsStaker(1000, 1001); } function testFail_ShouldNotBeAbleToVoteOnSameBlockAsProposalCreation() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // 112 200 000 UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112200000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112200000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } function testFail_TryVoteAfterProposalHasExpired() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 172800 + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112200000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112200000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } function testFail_TryVoteOnExecutedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_201_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); uint256 tokenID2 = stakeNFT.mintTo(address(user1), 1000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); user1.voteAsStaker(proposalID, tokenID2); } function testSameUserVoteWithDifferentPositions() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); for (uint256 i =0; i < 10; i++){ uint256 tokenID = stakeNFT.mintTo(address(user1), 112_20_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); } } function testFail_SameUserVoteWithSamePosition() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); user1.voteAsStaker(proposalID, tokenID); } function testFail_UserVoteWithNotOwnedPosition() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); UserAccount user2 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 200_000_000 * 10**18); uint256 tokenID1 = stakeNFT.mintTo(address(user1), 100_200_000 * 10**18, 1); uint256 tokenID2 = stakeNFT.mintTo(address(user2), 12_000_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID1); user1.voteAsStaker(proposalID, tokenID2); } function testExecuteProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("dummy:", address(dummy)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testVoteAndExecuteMultipleProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic1 = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); MockProposalLogic logic2 = new MockProposalLogic(); emit log_named_address("dummy:", address(dummy)); uint256 proposalID1 = governanceManager.propose(address(logic1)); assertProposal( governanceManager.getProposal(proposalID1), GovernanceStorage.Proposal( false, address(logic1), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID1)); uint256 proposalID2 = governanceManager.propose(address(logic2)); assertProposal( governanceManager.getProposal(proposalID2), GovernanceStorage.Proposal( false, address(logic2), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number+1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID1, tokenID); user.voteAsStaker(proposalID2, tokenID); } governanceManager.execute(proposalID1); assertProposal( governanceManager.getProposal(proposalID1), GovernanceStorage.Proposal( true, address(logic1), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID1)); governanceManager.execute(proposalID2); assertProposal( governanceManager.getProposal(proposalID2), GovernanceStorage.Proposal( true, address(logic2), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID2)); } function testExecuteProposalWhereSameUserVotesAsMinerAndStaker() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); UserAccount[10] memory users; madToken.approve(address(minerStake), 112_200_000 * 10**18); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); for (uint256 i =0; i < 10; i++){ users[i] = newUserAccount(madToken, minerStake, governanceManager); uint256 minerTokenId = minerStake.mintTo(address(users[i]), 5_610_000 * 10**18, 1); emit log_named_uint("miner token", minerTokenId); uint256 stakeTokenId = stakeNFT.mintTo(address(users[i]), 5_610_000 * 10**18, 1); emit log_named_uint("stake token", stakeTokenId); assertEq(minerTokenId, stakeTokenId); } for (uint256 i =0; i < 10; i++){ users[i].voteAsMiner(proposalID, i+1); users[i].voteAsStaker(proposalID, i+1); } governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testFail_TryToExecuteNonExistingProposalId() public { (,,,,GovernanceManager governanceManager) = getFixtureData(); governanceManager.execute(1000); } function testFail_ExecuteProposalWithoutVotingThreshold() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number + 172800 + 1); governanceManager.execute(proposalID); } function testFail_ExecuteAgainExecutedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogic logic = new MockProposalLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( true, address(logic), 112_200_000 * 10**18, 172800 ) ); assertTrue(governanceManager.isProposalExecuted(proposalID)); governanceManager.execute(proposalID); } function testFail_TryToExecuteProposalThatReverts() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicFailedLogic logic = new MockProposalLogicFailedLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); } function testExecuteProposalThatModifyStorage() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalChangeGovernanceManagerStorage logic = new MockProposalChangeGovernanceManagerStorage(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); // executing proposal that changes the stage. After execution, user // should be able to vote again in the proposal, we will be able to // rerun the proposal again, the stake and miner stake token should be // address 0, and threshold should be 1. governanceManager.execute(proposalID); assertTrue(!governanceManager.isProposalExecuted(proposalID)); assertEq(governanceManager.getMinerStakeTokenAddress(), address(0x0)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(0x0), 0, 666 ) ); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); // Changing the Stake address (zero address) MockProposalChangeGovernanceManagerStorageStake logic2 = new MockProposalChangeGovernanceManagerStorageStake(); uint256 proposalID2 = governanceManager.propose(address(logic2)); setBlockNumber(block.number +10); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); user1.voteAsStaker(proposalID2, tokenID); governanceManager.execute(proposalID2); assertEq(governanceManager.getStakeTokenAddress(), address(0x0)); } function testExecuteGovernanceAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicWithAllowedProposals logic = new MockProposalLogicWithAllowedProposals(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("Address dummy:", address(dummy)); NoGovernanceDelegateCall dummyDelegate = new NoGovernanceDelegateCall(); emit log_named_address("Address dummy delegate:", address(dummyDelegate)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); assertEq(governanceManager.allowedProposal(), address(0x0)); governanceManager.execute(proposalID); assertTrue(governanceManager.isProposalExecuted(proposalID)); assertEq(governanceManager.allowedProposal(), address(0x0)); } function testFail_ExecuteGovernanceWithoutAllowedProposal() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicWithOutAllowedProposals logic = new MockProposalLogicWithOutAllowedProposals(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); emit log_named_address("Address dummy:", address(dummy)); NoGovernanceDelegateCall dummyDelegate = new NoGovernanceDelegateCall(); emit log_named_address("Address dummy delegate:", address(dummyDelegate)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); // voting threshold = 112_200_000 * 10**18 shares UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); emit log_named_address("Address:", address(user1)); madToken.approve(address(stakeNFT), 220_000_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); assertEq(governanceManager.allowedProposal(), address(0x0)); governanceManager.execute(proposalID); } }
We can only vote after 1 block has passed from the proposal creation voting threshold = 112_200_000 * 10**18 shares
function testFail_TryToExecuteProposalThatReverts() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); MockProposalLogicFailedLogic logic = new MockProposalLogicFailedLogic(); MockGovernanceOnlyAction dummy = new MockGovernanceOnlyAction(address(governanceManager)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); setBlockNumber(block.number +1); UserAccount user1 = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 112_200_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user1), 112_200_000 * 10**18, 1); user1.voteAsStaker(proposalID, tokenID); governanceManager.execute(proposalID); }
6,387,430
[ 1, 3218, 848, 1338, 12501, 1839, 404, 1203, 711, 2275, 628, 326, 14708, 6710, 331, 17128, 5573, 273, 23543, 67, 6976, 67, 3784, 225, 13822, 28, 24123, 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, 1842, 3754, 67, 7833, 774, 5289, 14592, 18163, 426, 31537, 1435, 1071, 288, 203, 203, 3639, 261, 203, 5411, 934, 911, 50, 4464, 384, 911, 50, 4464, 16, 203, 5411, 5444, 264, 510, 911, 1131, 264, 510, 911, 16, 203, 5411, 490, 361, 1345, 9865, 312, 361, 1345, 16, 203, 5411, 7807, 3032, 3981, 16, 203, 5411, 611, 1643, 82, 1359, 1318, 314, 1643, 82, 1359, 1318, 203, 3639, 262, 273, 2812, 697, 10970, 751, 5621, 203, 203, 3639, 7867, 14592, 20556, 2925, 20556, 4058, 273, 394, 7867, 14592, 20556, 2925, 20556, 5621, 203, 3639, 7867, 43, 1643, 82, 1359, 3386, 1803, 9609, 273, 394, 7867, 43, 1643, 82, 1359, 3386, 1803, 12, 2867, 12, 75, 1643, 82, 1359, 1318, 10019, 203, 203, 3639, 2254, 5034, 14708, 734, 273, 314, 1643, 82, 1359, 1318, 18, 685, 4150, 12, 2867, 12, 28339, 10019, 203, 3639, 1815, 14592, 12, 203, 5411, 314, 1643, 82, 1359, 1318, 18, 588, 14592, 12, 685, 8016, 734, 3631, 203, 5411, 611, 1643, 82, 1359, 3245, 18, 14592, 12, 203, 7734, 629, 16, 203, 7734, 1758, 12, 28339, 3631, 203, 7734, 374, 16, 203, 7734, 8043, 6030, 713, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 1815, 5510, 12, 5, 75, 1643, 82, 1359, 1318, 18, 291, 14592, 23839, 12, 685, 8016, 734, 10019, 203, 3639, 444, 1768, 1854, 12, 2629, 18, 2696, 397, 21, 1769, 203, 3639, 2177, 3032, 729, 21, 273, 394, 1299, 3032, 12, 81, 361, 1345, 16, 384, 911, 50, 4464, 16, 314, 1643, 82, 2 ]
./partial_match/4/0xcC495748Df37dCfb0C1041a6FDfA257D350aFD60/sources/ERC721.sol
Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from owner to operator approvals Token name Token symbol Optional mapping for token URIs Base URI
{ using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping(address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string private _name; string private _symbol; mapping(uint256 => string) private _tokenURIs; string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; contract ERC721 is constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_baseURI).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_baseURI).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_baseURI).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } } return string(abi.encodePacked(_baseURI, tokenId.toString())); function baseURI() public view returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _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 { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } 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" ); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } d* function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function safeMint(address to, uint256 tokenId) public virtual { _safeMint(to, tokenId, ""); } */ 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" ); } 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); } function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } 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(ownerOf(tokenId), to, tokenId); } {} }
8,669,186
[ 1, 8867, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 45, 654, 39, 27, 5340, 12952, 12, 20, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 68, 9408, 628, 10438, 1758, 358, 3675, 261, 7924, 25121, 13, 444, 434, 16199, 2430, 6057, 25121, 2874, 628, 1147, 3258, 358, 3675, 25937, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 3155, 508, 3155, 3273, 4055, 2874, 364, 1147, 24565, 3360, 3699, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 565, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 654, 39, 27, 5340, 67, 27086, 20764, 273, 374, 92, 23014, 70, 27, 69, 3103, 31, 203, 203, 565, 2874, 12, 2867, 516, 6057, 25121, 694, 18, 5487, 694, 13, 3238, 389, 4505, 5157, 31, 203, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 389, 2316, 5460, 414, 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, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 565, 533, 3238, 389, 1969, 3098, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 27, 5340, 273, 374, 92, 3672, 1077, 8204, 4315, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 273, 374, 92, 25, 70, 25, 73, 24347, 74, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 2 ]
//Address: 0x95bE22039DA3114d17A38b9E7CD9b3576dE83924 //Contract name: EDColiseumAlpha //Balance: 0.0534375 Ether //Verification Date: 3/13/2018 //Transacion Count: 319 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /// @dev Interface to the Core Contract of Ether Dungeon. contract EDCoreInterface { /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _recruitHeroFee, uint _transportationFeeMultiplier, uint _noviceDungeonId, uint _consolationRewardsRequiredFaith, uint _challengeFeeMultiplier, uint _dungeonPreparationTime, uint _trainingFeeMultiplier, uint _equipmentTrainingFeeMultiplier, uint _preparationPeriodTrainingFeeMultiplier, uint _preparationPeriodEquipmentTrainingFeeMultiplier ); /** * @dev The external function to get all the relevant information about a specific player by its address. * @param _address The address of the player. */ function getPlayerDetails(address _address) external view returns ( uint dungeonId, uint payment, uint dungeonCount, uint heroCount, uint faith, bool firstHeroRecruited ); /** * @dev The external function to get all the relevant information about a specific dungeon by its ID. * @param _id The ID of the dungeon. */ function getDungeonDetails(uint _id) external view returns ( uint creationTime, uint status, uint difficulty, uint capacity, address owner, bool isReady, uint playerCount ); /** * @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error. * @param _id The ID of the dungeon. */ function getDungeonFloorDetails(uint _id) external view returns ( uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes ); /** * @dev The external function to get all the relevant information about a specific hero by its ID. * @param _id The ID of the hero. */ function getHeroDetails(uint _id) external view returns ( uint creationTime, uint cooldownStartTime, uint cooldownIndex, uint genes, address owner, bool isReady, uint cooldownRemainingTime ); /// @dev Get the attributes (equipments + stats) of a hero from its gene. function getHeroAttributes(uint _genes) public pure returns (uint[]); /// @dev Calculate the power of a hero from its gene, it calculates the equipment power, stats power, and super hero boost. function getHeroPower(uint _genes, uint _dungeonDifficulty) public pure returns ( uint totalPower, uint equipmentPower, uint statsPower, bool isSuper, uint superRank, uint superBoost ); /// @dev Calculate the power of a dungeon floor. function getDungeonPower(uint _genes) public pure returns (uint); /** * @dev Calculate the sum of top 5 heroes power a player owns. * The gas usage increased with the number of heroes a player owned, roughly 500 x hero count. * This is used in transport function only to calculate the required tranport fee. */ function calculateTop5HeroesPower(address _address, uint _dungeonId) public view returns (uint); } /// @dev Core Contract of "Enter the Coliseum" game of the ED (Ether Dungeon) Platform. contract EDColiseumAlpha is Pausable, ReentrancyGuard, Destructible { struct Participant { address player; uint heroId; uint heroPower; } /// @dev The address of the EtherDungeonCore contract. EDCoreInterface public edCoreContract = EDCoreInterface(0xf7eD56c1AC4d038e367a987258b86FC883b960a1); /// @dev Seed for the random number generator used for calculating fighting result. uint _seed; /* ======== SETTINGS ======== */ /// @dev The required win count to win a jackpot. uint public jackpotWinCount = 3; /// @dev The percentage of jackpot a player get when reaching the jackpotWinCount. uint public jackpotWinPercent = 50; /// @dev The percentage of rewards a player get when being the final winner of a tournament. uint public winPercent = 55; /// @dev The percentage of rewards a player get when being the final loser of a tournament, remaining will add to tournamentJackpot. uint public losePercent = 35; /// @dev Dungeon difficulty to be used when calculating super hero power boost, 1 is no boost. uint public dungeonDifficulty = 1; /// @dev The required fee to join a participant uint public participationFee = 0.02 ether; /// @dev The maximum number of participants for a tournament. uint public constant maxParticipantCount = 8; /* ======== STATE VARIABLES ======== */ /// @dev The next tournaments round number. uint public nextTournamentRound = 1; /// @dev The current accumulated rewards pool. uint public tournamentRewards; /// @dev The current accumulated jackpot. uint public tournamentJackpot = 0.2 ether; /// @dev Array of all the participant for next tournament. Participant[] public participants; /// @dev Array of all the participant for the previous tournament. Participant[] public previousParticipants; /// @dev Array to store the participant index all winners / losers for each "fighting round" of the previous tournament. uint[maxParticipantCount / 2] public firstRoundWinners; uint[maxParticipantCount / 4] public secondRoundWinners; uint[maxParticipantCount / 2] public firstRoundLosers; uint[maxParticipantCount / 4] public secondRoundLosers; uint public finalWinner; uint public finalLoser; /// @dev Mapping of hero ID to the hero's last participated tournament round to avoid repeated hero participation. mapping(uint => uint) public heroIdToLastRound; /// @dev Mapping of player ID to the consecutive win counts, used for calculating jackpot. mapping(address => uint) public playerToWinCounts; /* ======== EVENTS ======== */ /// @dev The PlayerTransported event is fired when user transported to another dungeon. event TournamentFinished(uint timestamp, uint tournamentRound, address finalWinner, address finalLoser, uint winnerRewards, uint loserRewards, uint winCount, uint jackpotRewards); /// @dev Payable constructor to pass in the initial jackpot ethers. function EDColiseum() public payable {} /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _jackpotWinCount, uint _jackpotWinPercent, uint _winPercent, uint _losePercent, uint _dungeonDifficulty, uint _participationFee, uint _maxParticipantCount ) { _jackpotWinCount = jackpotWinCount; _jackpotWinPercent = jackpotWinPercent; _winPercent = winPercent; _losePercent = losePercent; _dungeonDifficulty = dungeonDifficulty; _participationFee = participationFee; _maxParticipantCount = maxParticipantCount; } /// @dev The external function to get all the game settings in one call. function getNextTournamentData() external view returns ( uint _nextTournamentRound, uint _tournamentRewards, uint _tournamentJackpot, uint _participantCount ) { _nextTournamentRound = nextTournamentRound; _tournamentRewards = tournamentRewards; _tournamentJackpot = tournamentJackpot; _participantCount = participants.length; } /// @dev The external function to call when joining the next tournament. function joinTournament(uint _heroId) whenNotPaused nonReentrant external payable { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); // Throws if the hero is not owned by the sender. require(msg.sender == owner); // Throws if the hero is already participated in the next tournament. require(heroIdToLastRound[_heroId] != nextTournamentRound); // Throws if participation count is full. require(participants.length < maxParticipantCount); // Throws if payment not enough, any exceeding funds will be transferred back to the player. require(msg.value >= participationFee); tournamentRewards += participationFee; if (msg.value > participationFee) { msg.sender.transfer(msg.value - participationFee); } // Set the hero participation round. heroIdToLastRound[_heroId] = nextTournamentRound; // Get the hero power and set it to storage. uint heroPower; (heroPower,,,,) = edCoreContract.getHeroPower(genes, dungeonDifficulty); // Throw if heroPower is 12 (novice hero). require(heroPower > 12); // Set the participant data to storage. participants.push(Participant(msg.sender, _heroId, heroPower)); } /// @dev The onlyOwner external function to call when joining the next tournament. function startTournament() onlyOwner nonReentrant external { // Throws if participation count is not full. require(participants.length == maxParticipantCount); // FIGHT! _firstRoundFight(); _secondRoundWinnersFight(); _secondRoundLosersFight(); _finalRoundWinnersFight(); _finalRoundLosersFight(); // REWARDS! uint winnerRewards = tournamentRewards * winPercent / 100; uint loserRewards = tournamentRewards * losePercent / 100; uint addToJackpot = tournamentRewards - winnerRewards - loserRewards; address winner = participants[finalWinner].player; address loser = participants[finalLoser].player; winner.transfer(winnerRewards); loser.transfer(loserRewards); tournamentJackpot += addToJackpot; // JACKPOT! playerToWinCounts[winner]++; // Reset other participants' consecutive winCount. for (uint i = 0; i < participants.length; i++) { address participant = participants[i].player; if (participant != winner && playerToWinCounts[participant] != 0) { playerToWinCounts[participant] = 0; } } // Detemine if the winner have enough consecutive winnings for jackpot. uint jackpotRewards; uint winCount = playerToWinCounts[winner]; if (winCount == jackpotWinCount) { // Reset consecutive winCount of winner. playerToWinCounts[winner] = 0; jackpotRewards = tournamentJackpot * jackpotWinPercent / 100; tournamentJackpot -= jackpotRewards; winner.transfer(jackpotRewards); } // Reset tournament data and increment round. tournamentRewards = 0; previousParticipants = participants; participants.length = 0; nextTournamentRound++; // Emit TournamentFinished event. TournamentFinished(now, nextTournamentRound - 1, winner, loser, winnerRewards, loserRewards, winCount, jackpotRewards); } /// @dev The onlyOwner external function to call to cancel the next tournament and refunds. function cancelTournament() onlyOwner nonReentrant external { for (uint i = 0; i < participants.length; i++) { address participant = participants[i].player; if (participant != 0x0) { participant.transfer(participationFee); } } // Reset tournament data and increment round. tournamentRewards = 0; participants.length = 0; nextTournamentRound++; } /// @dev Withdraw all Ether from the contract. function withdrawBalance() onlyOwner external { // Can only withdraw if no participants joined (i.e. call cancelTournament first.) require(participants.length == 0); msg.sender.transfer(this.balance); } /* ======== SETTER FUNCTIONS ======== */ function setEdCoreContract(address _newEdCoreContract) onlyOwner external { edCoreContract = EDCoreInterface(_newEdCoreContract); } function setJackpotWinCount(uint _newJackpotWinCount) onlyOwner external { jackpotWinCount = _newJackpotWinCount; } function setJackpotWinPercent(uint _newJackpotWinPercent) onlyOwner external { jackpotWinPercent = _newJackpotWinPercent; } function setWinPercent(uint _newWinPercent) onlyOwner external { winPercent = _newWinPercent; } function setLosePercent(uint _newLosePercent) onlyOwner external { losePercent = _newLosePercent; } function setDungeonDifficulty(uint _newDungeonDifficulty) onlyOwner external { dungeonDifficulty = _newDungeonDifficulty; } function setParticipationFee(uint _newParticipationFee) onlyOwner external { participationFee = _newParticipationFee; } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /// @dev Compute all winners and losers for the first round. function _firstRoundFight() private { // Get all hero powers. uint heroPower0 = participants[0].heroPower; uint heroPower1 = participants[1].heroPower; uint heroPower2 = participants[2].heroPower; uint heroPower3 = participants[3].heroPower; uint heroPower4 = participants[4].heroPower; uint heroPower5 = participants[5].heroPower; uint heroPower6 = participants[6].heroPower; uint heroPower7 = participants[7].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { firstRoundWinners[0] = 0; firstRoundLosers[0] = 1; } else { firstRoundWinners[0] = 1; firstRoundLosers[0] = 0; } // 2 Vs 3 rand = _getRandomNumber(100); if ( (heroPower2 > heroPower3 && rand < 60) || (heroPower2 == heroPower3 && rand < 50) || (heroPower2 < heroPower3 && rand < 40) ) { firstRoundWinners[1] = 2; firstRoundLosers[1] = 3; } else { firstRoundWinners[1] = 3; firstRoundLosers[1] = 2; } // 4 Vs 5 rand = _getRandomNumber(100); if ( (heroPower4 > heroPower5 && rand < 60) || (heroPower4 == heroPower5 && rand < 50) || (heroPower4 < heroPower5 && rand < 40) ) { firstRoundWinners[2] = 4; firstRoundLosers[2] = 5; } else { firstRoundWinners[2] = 5; firstRoundLosers[2] = 4; } // 6 Vs 7 rand = _getRandomNumber(100); if ( (heroPower6 > heroPower7 && rand < 60) || (heroPower6 == heroPower7 && rand < 50) || (heroPower6 < heroPower7 && rand < 40) ) { firstRoundWinners[3] = 6; firstRoundLosers[3] = 7; } else { firstRoundWinners[3] = 7; firstRoundLosers[3] = 6; } } /// @dev Compute all second winners of all first round winners. function _secondRoundWinnersFight() private { // Get all hero powers of all first round winners. uint winner0 = firstRoundWinners[0]; uint winner1 = firstRoundWinners[1]; uint winner2 = firstRoundWinners[2]; uint winner3 = firstRoundWinners[3]; uint heroPower0 = participants[winner0].heroPower; uint heroPower1 = participants[winner1].heroPower; uint heroPower2 = participants[winner2].heroPower; uint heroPower3 = participants[winner3].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { secondRoundWinners[0] = winner0; } else { secondRoundWinners[0] = winner1; } // 2 Vs 3 rand = _getRandomNumber(100); if ( (heroPower2 > heroPower3 && rand < 60) || (heroPower2 == heroPower3 && rand < 50) || (heroPower2 < heroPower3 && rand < 40) ) { secondRoundWinners[1] = winner2; } else { secondRoundWinners[1] = winner3; } } /// @dev Compute all second losers of all first round losers. function _secondRoundLosersFight() private { // Get all hero powers of all first round losers. uint loser0 = firstRoundLosers[0]; uint loser1 = firstRoundLosers[1]; uint loser2 = firstRoundLosers[2]; uint loser3 = firstRoundLosers[3]; uint heroPower0 = participants[loser0].heroPower; uint heroPower1 = participants[loser1].heroPower; uint heroPower2 = participants[loser2].heroPower; uint heroPower3 = participants[loser3].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { secondRoundLosers[0] = loser1; } else { secondRoundLosers[0] = loser0; } // 2 Vs 3 rand = _getRandomNumber(100); if ( (heroPower2 > heroPower3 && rand < 60) || (heroPower2 == heroPower3 && rand < 50) || (heroPower2 < heroPower3 && rand < 40) ) { secondRoundLosers[1] = loser3; } else { secondRoundLosers[1] = loser2; } } /// @dev Compute the final winner. function _finalRoundWinnersFight() private { // Get all hero powers of all first round winners. uint winner0 = secondRoundWinners[0]; uint winner1 = secondRoundWinners[1]; uint heroPower0 = participants[winner0].heroPower; uint heroPower1 = participants[winner1].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { finalWinner = winner0; } else { finalWinner = winner1; } } /// @dev Compute the final loser. function _finalRoundLosersFight() private { // Get all hero powers of all first round winners. uint loser0 = secondRoundLosers[0]; uint loser1 = secondRoundLosers[1]; uint heroPower0 = participants[loser0].heroPower; uint heroPower1 = participants[loser1].heroPower; // Random number. uint rand; // 0 Vs 1 rand = _getRandomNumber(100); if ( (heroPower0 > heroPower1 && rand < 60) || (heroPower0 == heroPower1 && rand < 50) || (heroPower0 < heroPower1 && rand < 40) ) { finalLoser = loser1; } else { finalLoser = loser0; } } // @dev Return a pseudo random uint smaller than lower bounds. function _getRandomNumber(uint _upper) private returns (uint) { _seed = uint(keccak256( _seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty )); return _seed % _upper; } }
@dev The required win count to win a jackpot.
uint public jackpotWinCount = 3;
6,433,330
[ 1, 1986, 1931, 5657, 1056, 358, 5657, 279, 525, 484, 13130, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 525, 484, 13130, 18049, 1380, 273, 890, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/access/Whitelist.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol"; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "./Strings.sol"; import "./Medianizer.sol"; /** * @title Radi.Cards * This is the main Radi Cards NFT (ERC721) contract. It allows for the minting of * cards(NFTs) that can be sent to either a known EOA or to a claimable link. * ETH or DAI can be sent along with the card and the sender can choose a ratio * between a participating benefactor and the recipient, with no restriction. * Predefined cards can be added, with the artwork stored on IPFS. * The card message is stored within the smart contract. Cards can have a defined max * quantity that can be minted and a minimum purchase price. The claimable link sender * generates a public/private key pair that is used to take the NFT out of escrow (held within * this contract). The private key can then be sent to the recipient by email, * telergram, wechat ect. and is embedded within a URL to a claim page. When the user * opens the claim URL the private key is used to redeem the NFT and any associated gift (ETH/DAI). * @author blockrocket.tech (smart contracts) * @author cryptodecks.co * @author knownorigin.io * @author pheme.app * @author d1labs.com * @author mbdoesthings.com * @author chrismaree.io (smart contracts v2 update) */ contract RadiCards is ERC721Token, ERC721Holder, Whitelist { using SafeMath for uint256; // dai support StandardToken daiContract; Medianizer medianizerContract; string public tokenBaseURI = "https://ipfs.infura.io/ipfs/"; uint256 public tokenIdPointer = 0; struct Benefactor { address ethAddress; string name; string website; string logo; } struct CardDesign { string tokenURI; bool active; uint minted; uint maxQnty; //set to zero for unlimited //minimum price per card set in Atto (SI prefix for 1x10-18 dai) uint256 minPrice; //set to zero to default to the minimumContribution } // claimable link support enum Statuses { Empty, Deposited, Claimed, Cancelled } uint256 public EPHEMERAL_ADDRESS_FEE = 0.01 ether; mapping(address => uint256) public ephemeralWalletCards; // ephemeral wallet => tokenId struct RadiCard { address gifter; string message; bool daiDonation; uint256 giftAmount; uint256 donationAmount; Statuses status; uint256 cardIndex; uint256 benefactorIndex; } mapping(uint256 => Benefactor) public benefactors; uint256[] internal benefactorsIndex; mapping(uint256 => CardDesign) public cards; uint256[] internal cardsIndex; mapping(uint256 => RadiCard) public tokenIdToRadiCardIndex; //total gifted/donated in ETH uint256 public totalGiftedInWei; uint256 public totalDonatedInWei; //total gifted/donated in DAI uint256 public totalGiftedInAtto; //SI prefix for 1x10-18 dai is Atto. uint256 public totalDonatedInAtto; event CardGifted( address indexed _to, uint256 indexed _benefactorIndex, uint256 indexed _cardIndex, address _from, uint256 _tokenId, bool daiDonation, uint256 giftAmount, uint256 donationAmount, Statuses status ); event LogClaimGift( address indexed ephemeralAddress, address indexed sender, uint tokenId, address receiver, uint giftAmount, bool daiDonation ); event LogCancelGift( address indexed ephemeralAddress, address indexed sender, uint tokenId ); event BenefactorAdded( uint256 indexed _benefactorIndex ); event CardAdded( uint256 indexed _cardIndex ); constructor () public ERC721Token("RadiCards", "RADI") { addAddressToWhitelist(msg.sender); } function gift(address _to, uint256 _benefactorIndex, uint256 _cardIndex, string _message, uint256 _donationAmount, uint256 _giftAmount, bool _claimableLink) payable public returns (bool) { require(_to != address(0), "Must be a valid address"); if(_donationAmount > 0){ require(benefactors[_benefactorIndex].ethAddress != address(0), "Must specify existing benefactor"); } require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card"); require(cards[_cardIndex].active, "Must be an active card"); Statuses _giftStatus; address _sentToAddress; if(_claimableLink){ require(_donationAmount + _giftAmount + EPHEMERAL_ADDRESS_FEE == msg.value, "Can only request to donate and gift the amount of ether sent + Ephemeral fee"); _giftStatus = Statuses.Deposited; _sentToAddress = this; ephemeralWalletCards[_to] = tokenIdPointer; _to.transfer(EPHEMERAL_ADDRESS_FEE); } else { require(_donationAmount + _giftAmount == msg.value,"Can only request to donate and gift the amount of ether sent"); _giftStatus = Statuses.Claimed; _sentToAddress = _to; } if (cards[_cardIndex].maxQnty > 0){ //the max quantity is set to zero to indicate no limit. Only need to check that can mint if limited require(cards[_cardIndex].minted < cards[_cardIndex].maxQnty, "Can't exceed maximum quantity of card type"); } if(cards[_cardIndex].minPrice > 0){ //if the card has a minimum price check that enough has been sent // Convert the current value of the eth send to a USD value of atto (1 usd = 10^18 atto). // require(getEthUsdValue(msg.value) >= (cards[_cardIndex].minPrice), "Must send at least the minimum amount"); require (getMinCardPriceInWei(_cardIndex) <= msg.value,"Must send at least the minimum amount to buy card"); } tokenIdToRadiCardIndex[tokenIdPointer] = RadiCard({ gifter: msg.sender, message: _message, daiDonation: false, giftAmount: _giftAmount, donationAmount: _donationAmount, status: _giftStatus, cardIndex: _cardIndex, benefactorIndex: _benefactorIndex }); // Card is minted to the _sentToAddress. This is either this radicards contract(if claimableLink==true) // and the creator chose to use the escrow for a claimable link or to the recipient EOA directly uint256 _tokenId = _mint(_sentToAddress, cards[_cardIndex].tokenURI); cards[_cardIndex].minted++; // transfer the ETH to the benefactor if(_donationAmount > 0){ benefactors[_benefactorIndex].ethAddress.transfer(_donationAmount); totalDonatedInWei = totalDonatedInWei.add(_donationAmount); } // transfer gift to recipient. if(_giftAmount > 0){ totalGiftedInWei = totalGiftedInWei.add(_giftAmount); // note that we only do the transfer if the link is not claimable as if it is the eth sits in escrow within this contract if(!_claimableLink){ _sentToAddress.transfer(_giftAmount); } } emit CardGifted(_sentToAddress, _benefactorIndex, _cardIndex, msg.sender, _tokenId, false, _giftAmount, _donationAmount, _giftStatus); return true; } function giftInDai(address _to, uint256 _benefactorIndex, uint256 _cardIndex, string _message, uint256 _donationAmount, uint256 _giftAmount, bool _claimableLink) public payable returns (bool) { require(_to != address(0), "Must be a valid address"); if (_donationAmount > 0){ require(benefactors[_benefactorIndex].ethAddress != address(0), "Must specify existing benefactor"); } require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card"); require(cards[_cardIndex].active, "Must be an active card"); require((_donationAmount + _giftAmount) <= daiContract.allowance(msg.sender, this), "Must have provided high enough alowance to Radicard contract"); require((_donationAmount + _giftAmount) <= daiContract.balanceOf(msg.sender), "Must have enough token balance of dai to pay for donation and gift amount"); if (cards[_cardIndex].maxQnty > 0){ //the max quantity is set to zero to indicate no limit. Only need to check that can mint if limited require(cards[_cardIndex].minted < cards[_cardIndex].maxQnty, "Can't exceed maximum quantity of card type"); } if(cards[_cardIndex].minPrice > 0){ //if the card has a minimum price check that enough has been sent require((_donationAmount + _giftAmount) >= cards[_cardIndex].minPrice, "The total dai sent with the transaction is less than the min price of the token"); } //parameters that change based on the if the card is setup as with a claimable link Statuses _giftStatus; address _sentToAddress; if(_claimableLink){ require(msg.value == EPHEMERAL_ADDRESS_FEE, "A claimable link was generated but not enough ephemeral ether was sent!"); _giftStatus = Statuses.Deposited; _sentToAddress = this; // need to store the address of the ephemeral account and the card that it owns for claimable link functionality ephemeralWalletCards[_to] = tokenIdPointer; _to.transfer(EPHEMERAL_ADDRESS_FEE); } else { _giftStatus = Statuses.Claimed; _sentToAddress = _to; } tokenIdToRadiCardIndex[tokenIdPointer] = RadiCard({ gifter: msg.sender, message: _message, daiDonation: true, giftAmount: _giftAmount, donationAmount: _donationAmount, status: _giftStatus, cardIndex: _cardIndex, benefactorIndex: _benefactorIndex }); // Card is minted to the _sentToAddress. This is either this radicards contract(if claimableLink==true) // and the creator chose to use the escrow for a claimable link or to the recipient EOA directly uint256 _tokenId = _mint(_sentToAddress, cards[_cardIndex].tokenURI); cards[_cardIndex].minted++; // transfer the DAI to the benefactor if(_donationAmount > 0){ address _benefactorAddress = benefactors[_benefactorIndex].ethAddress; require(daiContract.transferFrom(msg.sender, _benefactorAddress, _donationAmount),"Sending to benefactor failed"); totalDonatedInAtto = totalDonatedInAtto.add(_donationAmount); } // transfer gift to recipient. note that this pattern is slightly different from the eth case as irrespective of // if it is a claimable link or not we preform the transaction. if it is indeed a claimable link the dai is sent // to the contract and held in escrow if(_giftAmount > 0){ require(daiContract.transferFrom(msg.sender, _sentToAddress, _giftAmount),"Sending to recipient failed"); totalGiftedInAtto = totalGiftedInAtto.add(_giftAmount); } emit CardGifted(_sentToAddress, _benefactorIndex, _cardIndex, msg.sender, _tokenId, true, _giftAmount, _donationAmount, _giftStatus); return true; } function _mint(address to, string tokenURI) internal returns (uint256 _tokenId) { uint256 tokenId = tokenIdPointer; super._mint(to, tokenId); _setTokenURI(tokenId, tokenURI); tokenIdPointer = tokenIdPointer.add(1); return tokenId; } function cancelGift(address _ephemeralAddress) public returns (bool) { uint256 tokenId = ephemeralWalletCards[_ephemeralAddress]; require(tokenId != 0, "Can only call this function on an address that was used as an ephemeral"); RadiCard storage card = tokenIdToRadiCardIndex[tokenId]; // is deposited and wasn't claimed or cancelled before require(card.status == Statuses.Deposited, "can only cancel gifts that are unclaimed (deposited)"); // only gifter can cancel transfer; require(msg.sender == card.gifter, "only the gifter of the card can cancel a gift"); // update status to cancelled card.status = Statuses.Cancelled; // transfer optional ether or dai back to creators address if (card.giftAmount > 0) { if(card.daiDonation){ require(daiContract.transfer(msg.sender, card.giftAmount),"Sending to recipient after cancel gift failed"); } else{ msg.sender.transfer(card.giftAmount); } } // send nft to buyer. for this we use a custom transfer function to take the nft out of escrow and // send it back to the buyer. transferFromEscrow(msg.sender, tokenId); // log cancel event emit LogCancelGift(_ephemeralAddress, msg.sender, tokenId); return true; } function claimGift(address _receiver) public returns (bool success) { // only holder of ephemeral private key can claim gift address _ephemeralAddress = msg.sender; uint256 tokenId = ephemeralWalletCards[_ephemeralAddress]; require(tokenId != 0, "The calling address does not have an ephemeral card associated with it"); RadiCard storage card = tokenIdToRadiCardIndex[tokenId]; // is deposited and wasn't claimed or cancelled before require(card.status == Statuses.Deposited, "Can only claim a gift that is unclaimed"); // update gift status to claimed card.status = Statuses.Claimed; // send nft to receiver transferFromEscrow(_receiver, tokenId); // transfer optional ether & dai to receiver's address if (card.giftAmount > 0) { if(card.daiDonation){ require(daiContract.transfer(_receiver, card.giftAmount),"Sending to recipient after cancel gift failed"); } else{ _receiver.transfer(card.giftAmount); } } // log claim event emit LogClaimGift( _ephemeralAddress, card.gifter, tokenId, _receiver, card.giftAmount, card.daiDonation ); return true; } function burn(uint256 _tokenId) public pure { revert("Radi.Cards are censorship resistant!"); } function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId), "token does not exist"); return Strings.strConcat(tokenBaseURI, tokenURIs[_tokenId]); } function tokenDetails(uint256 _tokenId) public view returns ( address _gifter, string _message, bool _daiDonation, uint256 _giftAmount, uint256 _donationAmount, Statuses status, uint256 _cardIndex, uint256 _benefactorIndex ) { require(exists(_tokenId), "token does not exist"); RadiCard memory _radiCard = tokenIdToRadiCardIndex[_tokenId]; return ( _radiCard.gifter, _radiCard.message, _radiCard.daiDonation, _radiCard.giftAmount, _radiCard.donationAmount, _radiCard.status, _radiCard.cardIndex, _radiCard.benefactorIndex ); } function tokenBenefactor(uint256 _tokenId) public view returns ( address _ethAddress, string _name, string _website, string _logo ) { require(exists(_tokenId),"Card must exist"); RadiCard memory _radiCard = tokenIdToRadiCardIndex[_tokenId]; Benefactor memory _benefactor = benefactors[_radiCard.benefactorIndex]; return ( _benefactor.ethAddress, _benefactor.name, _benefactor.website, _benefactor.logo ); } function tokensOf(address _owner) public view returns (uint256[] _tokenIds) { return ownedTokens[_owner]; } function benefactorsKeys() public view returns (uint256[] _keys) { return benefactorsIndex; } function cardsKeys() public view returns (uint256[] _keys) { return cardsIndex; } function addBenefactor(uint256 _benefactorIndex, address _ethAddress, string _name, string _website, string _logo) public onlyIfWhitelisted(msg.sender) returns (bool) { require(address(_ethAddress) != address(0), "Invalid address"); require(bytes(_name).length != 0, "Invalid name"); require(bytes(_website).length != 0, "Invalid name"); require(bytes(_logo).length != 0, "Invalid name"); benefactors[_benefactorIndex] = Benefactor( _ethAddress, _name, _website, _logo ); benefactorsIndex.push(_benefactorIndex); emit BenefactorAdded(_benefactorIndex); return true; } function addCard(uint256 _cardIndex, string _tokenURI, bool _active, uint256 _maxQnty, uint256 _minPrice) public onlyIfWhitelisted(msg.sender) returns (bool) { require(bytes(_tokenURI).length != 0, "Invalid token URI"); cards[_cardIndex] = CardDesign( _tokenURI, _active, 0, _maxQnty, _minPrice ); cardsIndex.push(_cardIndex); emit CardAdded(_cardIndex); return true; } function setTokenBaseURI(string _newBaseURI) external onlyIfWhitelisted(msg.sender) { require(bytes(_newBaseURI).length != 0, "Base URI invalid"); tokenBaseURI = _newBaseURI; } function setActive(uint256 _cardIndex, bool _active) external onlyIfWhitelisted(msg.sender) { require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card"); cards[_cardIndex].active = _active; } function setMaxQuantity(uint256 _cardIndex, uint256 _maxQnty) external onlyIfWhitelisted(msg.sender) { require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card"); require(cards[_cardIndex].minted <= _maxQnty, "Can't set the max quantity less than the current total minted"); cards[_cardIndex].maxQnty = _maxQnty; } function setMinPrice(uint256 _cardIndex, uint256 _minPrice) external onlyIfWhitelisted(msg.sender) { require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card"); cards[_cardIndex].minPrice = _minPrice; } function setDaiContractAddress(address _daiERC20ContractAddress) external onlyIfWhitelisted(msg.sender){ require(_daiERC20ContractAddress != address(0), "Must be a valid address"); daiContract = StandardToken(_daiERC20ContractAddress); } // sets the medianizer contract for the makerdao implementation used as a price oracle function setMedianizerContractAddress(address _MedianizerContractAddress) external onlyIfWhitelisted(msg.sender){ require(_MedianizerContractAddress != address(0), "Must be a valid address"); medianizerContract = Medianizer(_MedianizerContractAddress); } // returns the current ether price in usd. 18 decimal point precision used function getEtherPrice() public view returns(uint256){ return uint256(medianizerContract.read()); } // returns the value of ether in atto (1 usd of ether = 10^18 atto) function getEthUsdValue(uint256 _ether) public view returns(uint256){ return ((_ether*getEtherPrice())/(1 ether)); } // returns the minimum required in wei for a particular card given the card min price in dai function getMinCardPriceInWei(uint256 _cardIndex) public view returns(uint256){ return ((cards[_cardIndex].minPrice * 1 ether)/getEtherPrice()); } // transfer tokens held by this contract in escrow to the recipient. Used when either claiming or cancelling gifts function transferFromEscrow(address _recipient,uint256 _tokenId) internal{ require(super.ownerOf(_tokenId) == address(this),"The card must be owned by the contract for it to be in escrow"); super.clearApproval(this, _tokenId); super.removeTokenFrom(this, _tokenId); super.addTokenTo(_recipient, _tokenId); emit Transfer(this, _recipient, _tokenId); } }
SI prefix for 1x10-18 dai is Atto.
uint256 public totalGiftedInAtto;
12,580,752
[ 1, 2320, 1633, 364, 404, 92, 2163, 17, 2643, 5248, 77, 353, 6020, 83, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2078, 43, 2136, 329, 382, 3075, 83, 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 ]
pragma solidity 0.4.25; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner 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 != owner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title -Name Filter- v0.1.9 */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * Math operations with safety checks */ /** * @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; } } contract CelebrityGame is Ownable { using SafeMath for *; using NameFilter for string; string constant public gameName = "Celebrity Game"; // fired whenever a card is created event LogNewCard(string name, uint256 id); // fired whenever a player is registered event LogNewPlayer(string name, uint256 id); //just for isStartEnable modifier bool private isStart = false; uint256 private roundId = 0; struct Card { bytes32 name; // card owner name uint256 fame; // The number of times CARDS were liked uint256 fameValue; // The charge for the current card to be liked once uint256 notorious; // The number of times CARDS were disliked uint256 notoriousValue; // The charge for the current card to be disliked once } struct CardForPlayer { uint256 likeCount; // The number of times the player likes it uint256 dislikeCount; // The number of times the player disliked it } struct CardWinner { bytes32 likeWinner; bytes32 dislikeWinner; } Card[] public cards; bytes32[] public players; mapping (uint256 => mapping (uint256 => mapping ( uint256 => CardForPlayer))) public playerCard; // returns cards of this player like or dislike by playerId and roundId and cardId mapping (uint256 => mapping (uint256 => CardWinner)) public cardWinnerMap; // (roundId => (cardId => winner)) returns winner by roundId and cardId mapping (uint256 => Card[]) public rounCardMap; // returns Card info by roundId mapping (bytes32 => uint256) private plyNameXId; // (playerName => Id) returns playerId by playerName mapping (bytes32 => uint256) private cardNameXId; // (cardName => Id) returns cardId by cardName mapping (bytes32 => bool) private cardIsReg; // (cardName => cardCount) returns cardCount by cardName,just for createCard function mapping (bytes32 => bool) private playerIsReg; // (playerName => isRegister) returns registerInfo by playerName, just for registerPlayer funciton mapping (uint256 => bool) private cardIdIsReg; // (cardId => card info) returns card info by cardId mapping (uint256 => bool) private playerIdIsReg; // (playerId => id) returns player index of players by playerId mapping (uint256 => uint256) private cardIdXSeq; mapping (uint256 => uint256) private playerIdXSeq; /** * @dev used to make sure no one can interact with contract until it has been started */ modifier isStartEnable { require(isStart == true); _; } /** * the contract precision is 1000 */ constructor() public { string[8] memory names= ["SatoshiNakamoto","CZ","HeYi","LiXiaolai","GuoHongcai","VitalikButerin","StarXu","ByteMaster"]; uint256[8] memory _ids = [uint256(183946248739),536269148721,762415028463,432184367532,398234673241,264398721023,464325189620,217546321806]; for (uint i = 0; i < 8; i++){ string memory _nameString = names[i]; uint256 _id = _ids[i]; bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == false); uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1; cardIdXSeq[_id] = _seq; cardNameXId[_name] = _id; cardIsReg[_name] = true; cardIdIsReg[_id] = true; } } /** * @dev use this function to create card. * - must pay some create fees. * - name must be unique * - max length of 32 characters long * @param _nameString owner desired name for card * @param _id card id * (this might cost a lot of gas) */ function createCard(string _nameString, uint256 _id) public onlyOwner() { require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked(""))); bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == false); uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1; cardIdXSeq[_id] = _seq; cardNameXId[_name] = _id; cardIsReg[_name] = true; cardIdIsReg[_id] = true; emit LogNewCard(_nameString, _id); } /** * @dev use this function to register player. * - must pay some register fees. * - name must be unique * - name cannot be null * - max length of 32 characters long * @param _nameString team desired name for player * @param _id player id * (this might cost a lot of gas) */ function registerPlayer(string _nameString, uint256 _id) external { require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked(""))); bytes32 _name = _nameString.nameFilter(); require(playerIsReg[_name] == false); uint256 _seq = players.push(_name) - 1; playerIdXSeq[_id] = _seq; plyNameXId[_name] = _id; playerIsReg[_name] = true; playerIdIsReg[_id] = true; emit LogNewPlayer(_nameString, _id); } /** * @dev this function for One player likes the CARD once. * @param _cardId must be returned when creating CARD * @param _playerId must be returned when registering player * (this might cost a lot of gas) */ function likeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable { require(cardIdIsReg[_cardId] == true, "sorry create this card first"); require(playerIdIsReg[_playerId] == true, "sorry register the player name first"); Card storage queryCard = cards[cardIdXSeq[_cardId]]; queryCard.fame = queryCard.fame.add(1); queryCard.fameValue = queryCard.fameValue.add(queryCard.fameValue / 100*1000); playerCard[_playerId][roundId][_cardId].likeCount == (playerCard[_playerId][roundId][_cardId].likeCount).add(1); cardWinnerMap[roundId][_cardId].likeWinner = players[playerIdXSeq[_playerId]]; } /** * @dev this function for One player dislikes the CARD once. * @param _cardId must be returned when creating CARD * @param _playerId must be created when registering player * (this might cost a lot of gas) */ function dislikeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable { require(cardIdIsReg[_cardId] == true, "sorry create this card first"); require(playerIdIsReg[_playerId] == true, "sorry register the player name first"); Card storage queryCard = cards[cardIdXSeq[_cardId]]; queryCard.notorious = queryCard.notorious.add(1); queryCard.notoriousValue = queryCard.notoriousValue.add(queryCard.notoriousValue / 100*1000); playerCard[_playerId][roundId][_cardId].dislikeCount == (playerCard[_playerId][roundId][_cardId].dislikeCount).add(1); cardWinnerMap[roundId][_cardId].dislikeWinner = players[playerIdXSeq[_playerId]]; } /** * @dev use this function to reset card properties. * - must be called when game is not started by team. * @param _id must be returned when creating CARD * (this might cost a lot of gas) */ function reset(uint256 _id) external onlyOwner() { require(isStart == false); Card storage queryCard = cards[cardIdXSeq[_id]]; queryCard.fame = 1; queryCard.fameValue = 1000; queryCard.notorious = 1; queryCard.notoriousValue = 1000; } /** * @dev use this function to start the game. * - must be called by owner. * (this might cost a lot of gas) */ function gameStart() external onlyOwner() { isStart = true; roundId = roundId.add(1); } /** * @dev use this function to end the game. Just for emergency control by owner * (this might cost a lot of gas) */ function gameEnd() external onlyOwner() { isStart = false; rounCardMap[roundId] = cards; } /** * @dev use this function to get CARDS count * @return Total all CARDS in the current game */ function getCardsCount() public view returns(uint256) { return cards.length; } /** * @dev use this function to get CARDS id by its name. * @param _nameString must be created when creating CARD * @return the card id */ function getCardId(string _nameString) public view returns(uint256) { bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == true, "sorry create this card first"); return cardNameXId[_name]; } /** * @dev use this function to get player id by the name. * @param _nameString must be created when creating CARD * @return the player id */ function getPlayerId(string _nameString) public view returns(uint256) { bytes32 _name = _nameString.nameFilter(); require(playerIsReg[_name] == true, "sorry register the player name first"); return plyNameXId[_name]; } /** * @dev use this function to get player bet count. * @param _playerName must be created when registering player * @param _roundId must be a game that has already started * @param _cardName the player id must be created when creating CARD * @return likeCount * @return dislikeCount */ function getPlayerBetCount(string _playerName, uint256 _roundId, string _cardName) public view returns(uint256 likeCount, uint256 dislikeCount) { bytes32 _cardNameByte = _cardName.nameFilter(); require(cardIsReg[_cardNameByte] == false); bytes32 _playerNameByte = _playerName.nameFilter(); require(playerIsReg[_playerNameByte] == false); return (playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].likeCount, playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].dislikeCount); } }
* @dev use this function to get CARDS id by its name. @param _nameString must be created when creating CARD @return the card id/
function getCardId(string _nameString) public view returns(uint256) { bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == true, "sorry create this card first"); return cardNameXId[_name]; }
12,614,185
[ 1, 1202, 333, 445, 358, 336, 385, 985, 3948, 612, 635, 2097, 508, 18, 225, 389, 529, 780, 1297, 506, 2522, 1347, 4979, 385, 8085, 327, 326, 5270, 612, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 26776, 548, 12, 1080, 389, 529, 780, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 1731, 1578, 389, 529, 273, 389, 529, 780, 18, 529, 1586, 5621, 203, 3639, 2583, 12, 3327, 2520, 1617, 63, 67, 529, 65, 422, 638, 16, 315, 2467, 1176, 752, 333, 5270, 1122, 8863, 203, 3639, 327, 5270, 461, 60, 548, 63, 67, 529, 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 ]
pragma solidity ^0.4.19; import "./ERC725.sol"; import "./ERC735.sol"; contract PersonaIdentity is ERC725, ERC735 { mapping (address => uint256) keys; mapping (uint256 => address[]) keysByType; mapping (bytes32 => Claim) claims; mapping (uint256 => bytes32[]) claimsByType; mapping (bytes32 => uint256) claimPositions; mapping (bytes32 => Transaction) transactions; uint nonce = 0; struct Transaction { address to; uint256 value; bytes32 data; uint256 nonce; } modifier managerOnly { require(keys[msg.sender] == MANAGEMENT_KEY); _; } modifier managerOrSelf { require(keys[msg.sender] == MANAGEMENT_KEY || msg.sender == address(this)); _; } modifier actorOnly { require(keys[msg.sender] == ACTION_KEY); _; } modifier claimSignerOnly { require(keys[msg.sender] == CLAIM_SIGNER_KEY); _; } function PersonaIdentity() public { _addKey(msg.sender, MANAGEMENT_KEY); } // Adds a _key to the identity. The _purpose specifies the purpose of key. Initially we propose four purposes: // 1: MANAGEMENT keys, which can manage the identity // 2: ACTION keys, which perform actions in this identities name (signing, logins, transactions, etc.) // 3: CLAIM signer keys, used to sign claims on other identities which need to be revokable. // 4: ENCRYPTION keys, used to encrypt data e.g. hold in claims. // MUST only be done by keys of purpose 1, or the identity itself. If its the identity itself, the approval process will determine its approval. // Triggers Event KeyAdded function addKey(address _key, uint256 _type) public managerOrSelf returns (bool success) { _addKey(_key, _type); KeyAdded(_key, _type); } // Replaces key by adding new key then removing old key // Triggers Event KeyAdded // Triggers Event KeyRemoved function replaceKey(address _oldKey, address _newKey) public managerOrSelf returns (bool success) { _addKey(_newKey, getKeyType(_oldKey)); _removeKey(_oldKey); return true; } //Removes _key from the identity. //MUST only be done by keys of purpose 1, or the identity itself. If its the identity itself, the approval process will determine its approval. function removeKey(address _key) public managerOrSelf returns (bool success) { _removeKey(_key); KeyRemoved(_key, getKeyType(_key)); } // Executes an action on other contracts, or itself, or a transfer of ether. // SHOULD require approve to be called with one or more keys of purpose 1 or 2 to approve this execution. // Triggers Event ExecutionRequested // Triggers on direct execution Event: Executed function execute(address _to, uint256 _value, bytes32 _data) public returns (bytes32 executionId) { uint256 senderKey = keys[msg.sender]; require(senderKey == MANAGEMENT_KEY || senderKey == ACTION_KEY); executionId = keccak256(_to, _value, _data, nonce); transactions[executionId] = Transaction ( { to: _to, value: _value, data: _data, nonce: nonce }); if (senderKey == MANAGEMENT_KEY) { approve(executionId, true); } ExecutionRequested(executionId, _to, _value, _data); } // Approves an execution or claim addition. // This SHOULD require n of m approvals of keys purpose 1, if the _to of the execution is the identity contract itself, to successfull approve an execution. // And COULD require n of m approvals of keys purpose 2, if the _to of the execution is another contract, to successfull approve an execution. // Triggers Event: Approved // Triggers on successfull execution Event: Executed // Triggers on successfull claim addition Event: ClaimAdded function approve(bytes32 _id, bool _approve) public managerOnly returns (bool success) { require(transactions[_id].nonce == nonce); nonce++; if (_approve) { success = transactions[_id].to.call.value(transactions[_id].value)(transactions); if (success) { Executed(_id, transactions[_id].to, transactions[_id].value, transactions[_id].data); } } Approved(_id, _approve); } function addClaim(uint256 _claimType, address _issuer, uint256 _signatureType, bytes32 _signature, bytes32 _claim, string _uri) public claimSignerOnly returns (bytes32 claimId) { claimId = keccak256(_issuer, _claimType); claims[claimId] = Claim( { claimType: _claimType, issuer: _issuer, signatureType: _signatureType, signature: _signature, claim: _claim, uri: _uri } ); claimPositions[keccak256(_issuer, _claimType)] = claimsByType[_claimType].length; claimsByType[_claimType].push(claimId); } function removeClaim(bytes32 _claimId) public returns (bool success) { Claim memory claim = claims[_claimId]; require(msg.sender == claim.issuer || keys[msg.sender] == MANAGEMENT_KEY || msg.sender == address(this)); uint claimIdTypePos = claimPositions[_claimId]; delete claimPositions[_claimId]; bytes32[] storage claimsTypeArr = claimsByType[claim.claimType]; bytes32 replacer = claimsTypeArr[claimsTypeArr.length-1]; claimsTypeArr[claimIdTypePos] = replacer; claimPositions[replacer] = claimIdTypePos; delete claims[_claimId]; claimsTypeArr.length--; return true; } function _addKey(address _key, uint256 _type) private { require(keys[_key] == 0); keys[_key] = _type; claimPositions[keccak256(_key, _type)] = keysByType[_type].length; keysByType[_type].push(_key); KeyAdded(_key, _type); } function _removeKey(address _key) private { uint256 keyType = keys[_key]; address[] storage keyArr = keysByType[keyType]; if (msg.sender != address(this) && keyType == MANAGEMENT_KEY && keyArr.length == 1) { revert(); } bytes32 oldIndex = keccak256(_key, keyType); uint index = claimPositions[oldIndex]; delete claimPositions[oldIndex]; address replacer = keyArr[keyArr.length - 1]; keyArr[index] = replacer; claimPositions[keccak256(replacer, keys[replacer])] = index; keyArr.length--; delete keys[_key]; KeyRemoved(_key, keyType); } // Return the purpose of the key if held by this Identity // If not held, return 0 function getKeyType(address _key) public constant returns(uint256 keyType) { return keys[_key]; } // Return the purpose of the key if held by this Identity // If not held, return 0 function getKeysByType(uint256 _type) public constant returns(address[] _keys) { return keysByType[_type]; } function getClaim(bytes32 _claimId) public constant returns(uint256 claimType, address issuer, uint256 signatureType, bytes32 signature, bytes32 claim, string uri) { Claim memory _claim = claims[_claimId]; return (_claim.claimType, _claim.issuer, _claim.signatureType, _claim.signature, _claim.claim, _claim.uri); } function getClaimsIdByType(uint256 _claimType) public constant returns(bytes32[]) { return claimsByType[_claimType]; } }
Return the purpose of the key if held by this Identity If not held, return 0
function getKeysByType(uint256 _type) public constant returns(address[] _keys) { return keysByType[_type]; }
5,378,060
[ 1, 990, 326, 13115, 434, 326, 498, 309, 15770, 635, 333, 7808, 971, 486, 15770, 16, 327, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24753, 14145, 12, 11890, 5034, 389, 723, 13, 1071, 5381, 1135, 12, 2867, 8526, 389, 2452, 13, 288, 203, 3639, 327, 1311, 14145, 63, 67, 723, 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 ]
pragma solidity ^0.8.11; import {Assert} from "truffle/Assert.sol"; import {NoughtsCrosses} from "../../contracts/Games/NoughtsCrosses.sol"; contract TestNoughtsCrosses is NoughtsCrosses { function testAbs8() public { uint8 result = _abs8(int8(1)); Assert.equal(result, uint8(1), "Result should be : |1| == 1"); result = _abs8(int8(-1)); Assert.equal(result, uint8(1), "Result should be : |-1| == 1"); result = _abs8(int8(0)); Assert.equal(result, uint8(0), "Result should be : |0| == 0"); } function playerDoesntExist() public { uint8[2] memory coord = [uint8(0), uint8(0)]; uint8[frameSize][frameSize] memory frame = generateGameFrame(); frame = _action(coord, frame, 2); } function coordDoesntExist() public { uint8[2] memory coord = [uint8(0), uint8(4)]; uint8[frameSize][frameSize] memory frame = generateGameFrame(); frame = _action(coord, frame, 0); } function testAction() public { bool r; uint8[2] memory coord = [uint8(0), uint8(0)]; uint8[frameSize][frameSize] memory frame = generateGameFrame(); frame = _action(coord, frame, 0); uint8 result = frame[0][0]; Assert.equal(result, uint8(1), "Player 1 set value 1 to [0, 0]."); coord = [uint8(0), uint8(1)]; frame = _action(coord, frame, 1); result = frame[0][1]; Assert.equal(result, uint8(4), "Player 2 set value 4 to [0, 1]."); // Test player 3 can't play (r, ) = address(this).call( abi.encodePacked(this.playerDoesntExist.selector) ); Assert.isFalse(r, "There are only 2 players (0-indexed)."); // Test override a value coord = [uint8(0), uint8(1)]; frame = _action(coord, frame, 0); result = frame[0][1]; Assert.equal(result, uint8(1), "Player 1 set value 1 to [0, 1]."); // Test an impossible pairwise. (r, ) = address(this).call( abi.encodePacked(this.coordDoesntExist.selector) ); Assert.isFalse(r, "The frame only contains 3x3 box (0-indexed)."); } // Expected usage with value 1 and 4 function testCheckWinnerExpectedUsage() public { uint8[frameSize][frameSize] memory frame = generateGameFrame(); frame[0] = [uint8(1), uint8(1), uint8(1)]; // Test horizontal bool result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isFalse(result, "Player 2 lost."); frame[0] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[1] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); // Test vertical frame[2] = [uint8(4), uint8(1), uint8(1)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[2] = [uint8(1), uint8(4), uint8(1)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); // Test right diagonal frame[0] = [uint8(4), uint8(4), uint8(1)]; frame[1] = [uint8(4), uint8(1), uint8(4)]; frame[2] = [uint8(1), uint8(4), uint8(4)]; result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isFalse(result, "Player 2 lost."); // Test left diagonal frame[1] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); // Both won frame[0] = [uint8(4), uint8(4), uint8(1)]; frame[1] = [uint8(4), uint8(1), uint8(1)]; frame[2] = [uint8(4), uint8(4), uint8(1)]; result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); } }
Expected usage with value 1 and 4 Test horizontal Test vertical Test right diagonal Test left diagonal Both won
function testCheckWinnerExpectedUsage() public { uint8[frameSize][frameSize] memory frame = generateGameFrame(); frame[0] = [uint8(1), uint8(1), uint8(1)]; bool result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isFalse(result, "Player 2 lost."); frame[0] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[1] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[2] = [uint8(4), uint8(1), uint8(1)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[2] = [uint8(1), uint8(4), uint8(1)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[0] = [uint8(4), uint8(4), uint8(1)]; frame[1] = [uint8(4), uint8(1), uint8(4)]; frame[2] = [uint8(1), uint8(4), uint8(4)]; result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isFalse(result, "Player 2 lost."); frame[1] = [uint8(4), uint8(4), uint8(4)]; result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); result = checkWinner(frame, 0); Assert.isFalse(result, "Player 1 lost."); frame[0] = [uint8(4), uint8(4), uint8(1)]; frame[1] = [uint8(4), uint8(1), uint8(1)]; frame[2] = [uint8(4), uint8(4), uint8(1)]; result = checkWinner(frame, 0); Assert.isTrue(result, "Player 1 won."); result = checkWinner(frame, 1); Assert.isTrue(result, "Player 2 won."); }
5,433,059
[ 1, 6861, 4084, 598, 460, 404, 471, 1059, 7766, 10300, 7766, 9768, 7766, 2145, 15425, 7766, 2002, 15425, 19118, 8462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 1564, 59, 7872, 6861, 5357, 1435, 1071, 288, 203, 3639, 2254, 28, 63, 3789, 1225, 6362, 3789, 1225, 65, 3778, 2623, 273, 2103, 12496, 3219, 5621, 203, 3639, 2623, 63, 20, 65, 273, 306, 11890, 28, 12, 21, 3631, 2254, 28, 12, 21, 3631, 2254, 28, 12, 21, 13, 15533, 203, 203, 3639, 1426, 563, 273, 866, 59, 7872, 12, 3789, 16, 374, 1769, 203, 3639, 5452, 18, 291, 5510, 12, 2088, 16, 315, 12148, 404, 8462, 1199, 1769, 203, 3639, 563, 273, 866, 59, 7872, 12, 3789, 16, 404, 1769, 203, 3639, 5452, 18, 291, 8381, 12, 2088, 16, 315, 12148, 576, 13557, 1199, 1769, 203, 203, 3639, 2623, 63, 20, 65, 273, 306, 11890, 28, 12, 24, 3631, 2254, 28, 12, 24, 3631, 2254, 28, 12, 24, 13, 15533, 203, 3639, 563, 273, 866, 59, 7872, 12, 3789, 16, 404, 1769, 203, 3639, 5452, 18, 291, 5510, 12, 2088, 16, 315, 12148, 576, 8462, 1199, 1769, 203, 3639, 563, 273, 866, 59, 7872, 12, 3789, 16, 374, 1769, 203, 3639, 5452, 18, 291, 8381, 12, 2088, 16, 315, 12148, 404, 13557, 1199, 1769, 203, 203, 3639, 2623, 63, 21, 65, 273, 306, 11890, 28, 12, 24, 3631, 2254, 28, 12, 24, 3631, 2254, 28, 12, 24, 13, 15533, 203, 3639, 563, 273, 866, 59, 7872, 12, 3789, 16, 404, 1769, 203, 3639, 5452, 18, 291, 5510, 12, 2088, 16, 315, 12148, 576, 8462, 1199, 1769, 203, 3639, 563, 273, 866, 59, 7872, 12, 3789, 16, 374, 1769, 203, 3639, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import './ICompound.sol'; interface ICAPFactory { function createCrowdProposal(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) external; } contract RequestForProposal { /// @dev `COMP` token contract address address public immutable comp; /// @dev Crowd Proposal factory contract address address public immutable CAPFactory; // Should we let governor alpha reclaim lost funds? /// @dev Minimum duration for a RFP uint256 public minDuration; /// @notice Status of a Proposal enum RFPStatus { open, closed, awarded, expired, cancelled, proposed } /// @notice Status of a Submission enum RFPSubmissionStatus { submitted, selected, proposed, rejected } /// @dev The number of RFP's in the system /// @dev This should be replaces with OpenZeppelin Counters uint256 public RFPCount; /// @dev Describes the components of a Request for Proposal struct RFP { address requestor; uint256 id; uint256 submissionDate; uint256 expiry; string requestDescription; uint256 bounty; RFPStatus status; bool awarded; } /// @dev Mapping of Request for proposals by integer mapping(uint => RFP) requestsForProposals; /// @dev Descibes the contents of a RFP submission struct Submission { uint256 RFPId; address creator; string submissionDescription; RFPSubmissionStatus status; address[] targets; uint256[] values; string[] signatures; bytes[] calldatas; string description; } /// @dev Library of all RFP submissions mapping RFPId to submission ids mapping(uint => mapping(uint => Submission)) submissions; /// @notice A count of all submissions uint256 public submissionCount; /// @notice An event emitted on the creation of a RFP event RFPCreated(address indexed creator, uint256 bounty, uint256 expiry, string description ); /// @notice An event emitted on the change of state of a RFP event RFPStatusChanged(uint256 RFPId, RFPStatus Status); /// @notice An event emitted on the submission of a Proposal to a RFP event SubmissionCreated(address indexed creator, uint256 RFPId); /// @notice An event emitted on the change of status of a Proposal event SubmissionChanged(uint RFP, uint SubmissionId, RFPSubmissionStatus status); constructor(address capFactory_, address comp_, uint256 minDuration_) public { CAPFactory = capFactory_; comp = comp_; minDuration = minDuration_; } /** * @notice Create a new Request for Proposal * @notice Call 'Comp.approve(RFP_Contract_Address, compStakeAmount') before calling this method * @param requestDescription The offChain source of human readable description about the RFP * @param expiry The Expiration date at which the RFP is no longer valid * @param bounty The bounty, in COMP that will be paid out on accepted request */ function createRFP(string memory requestDescription, uint256 expiry, uint256 bounty) external { //Get the bounty and lock it up require(IComp(comp).transferFrom(msg.sender, address(this), bounty), "Failed to receive bounty"); //Make sure expiration date is after now require(expiry > block.number+minDuration, "Expiration date must be minDuration in the future"); RFP memory rfp; uint256 currentCount = RFPCount + 1; RFPCount++; rfp.requestor = msg.sender; rfp.id = currentCount; rfp.submissionDate = block.number; rfp.expiry = expiry; rfp.requestDescription = requestDescription; rfp.bounty = bounty; rfp.status = RFPStatus.open; rfp.awarded = false; requestsForProposals[currentCount] = rfp; emit RFPCreated(msg.sender, bounty, expiry, requestDescription); } function submitRFP( uint RFPId, string memory submissionDescription, address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) external { //Require that the RFP is open require(requestsForProposals[RFPId].status == RFPStatus.open, "RFP is not open for submissions"); Submission memory submission; uint256 currentSubCount = submissionCount; submissionCount++; submission.RFPId = RFPId; submission.submissionDescription = submissionDescription; submission.status = RFPSubmissionStatus.submitted; submission.targets = targets; submission.values = values; submission.signatures = signatures; submission.calldatas = calldatas; submission.description = description; submissions[RFPId][currentSubCount] = submission; emit SubmissionCreated(msg.sender, RFPId); } /** * @notice Cancel an existing Reuest for Proposal and receive bounty back * @notice This will need better reentrancy guards * @param id The ID of the Request for Proposal */ function cancelRFP(uint id) external { //Require the msg.sender to be the RFP Creator require(requestsForProposals[id].requestor == msg.sender, "Only the RFP creator can cancel"); //Require that the proposal has not alrady been paid out require(requestsForProposals[id].awarded == false, "RFP has already been paid out"); //Add better re-entrancy guards uint256 payout = requestsForProposals[id].bounty; //set proposal bounty to zero requestsForProposals[id].bounty = 0; requestsForProposals[id].status = RFPStatus.cancelled; //Return funds IComp(comp).transferFrom(address(this), msg.sender, payout); emit RFPStatusChanged(id, RFPStatus.cancelled); } /** * @notice Award an RFP Submission * @notice This will nee beter reentrancy guards * @param rfpId The ID of the request for Proposal * @param submissionId The ID of the submission to the RFP being awarded */ function awardRFP(uint256 rfpId, uint256 submissionId) external { /// Required the creator of the RFP to award require(requestsForProposals[rfpId].requestor == msg.sender, "Only the RFP creator can award"); /// Require the RFP is actually open require(requestsForProposals[rfpId].status == RFPStatus.open, "RFP is not open and can not be awarded"); /// Require the RFP has not expired require(requestsForProposals[rfpId].expiry < block.number, "RFP has expired"); /// Require that the RFP proposal is "submitted" require(submissions[rfpId][submissionId].status == RFPSubmissionStatus.submitted, "RFP Proposal is not in Submitted State"); requestsForProposals[rfpId].status = RFPStatus.awarded; submissions[rfpId][submissionId].status = RFPSubmissionStatus.selected; //Need better re-entrancy protection here. uint256 bounty = requestsForProposals[rfpId].bounty; requestsForProposals[rfpId].bounty = 0; //Send the bounty=, what happens if this fails? IComp(comp).transferFrom(address(this), submissions[rfpId][submissionId].creator, bounty); emit SubmissionChanged(rfpId, submissionId, submissions[rfpId][submissionId].status); } /** * @notice Submit an approved submission to the COMP CrowdProposalFactory * @notice Anyone can submit, but it must be an approved and paid out proposal * @notice The submiter must also have enough Comp allowance to succesfullly make the crowdProposal * @param rfpId The ID of the request for Proposal * @param submissionId The ID of the submission to the RFP being awarded */ function submitToCAP(uint256 rfpId, uint256 submissionId) external { /// Require the Proposal to have been selected (maybe not nessesary but for now we let it slide) require(submissions[rfpId][submissionId].status == RFPSubmissionStatus.selected, "Proposal was not selected"); //Mark Status as submitted (if anyone would reentrant this?) submissions[rfpId][submissionId].status = RFPSubmissionStatus.proposed; ICAPFactory(CAPFactory).createCrowdProposal( submissions[rfpId][submissionId].targets, submissions[rfpId][submissionId].values, submissions[rfpId][submissionId].signatures, submissions[rfpId][submissionId].calldatas, submissions[rfpId][submissionId].description ); emit SubmissionChanged(rfpId, submissionId,submissions[rfpId][submissionId].status); } //Todo //function getRFPStatus(uint256 RFPIs) public {} //function getProposalStatus() {} //function letCompGovernorReclaimLostFunds }
Require that the RFP is open
function submitRFP( uint RFPId, string memory submissionDescription, address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) external { require(requestsForProposals[RFPId].status == RFPStatus.open, "RFP is not open for submissions"); Submission memory submission; uint256 currentSubCount = submissionCount; submissionCount++; submission.RFPId = RFPId; submission.submissionDescription = submissionDescription; submission.status = RFPSubmissionStatus.submitted; submission.targets = targets; submission.values = values; submission.signatures = signatures; submission.calldatas = calldatas; submission.description = description; submissions[RFPId][currentSubCount] = submission; emit SubmissionCreated(msg.sender, RFPId); }
13,130,938
[ 1, 8115, 716, 326, 534, 30246, 353, 1696, 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, 4879, 12918, 52, 12, 203, 3639, 2254, 534, 30246, 548, 16, 203, 3639, 533, 3778, 8515, 3291, 16, 203, 3639, 1758, 8526, 3778, 5774, 16, 203, 3639, 2254, 5034, 8526, 3778, 924, 16, 203, 3639, 533, 8526, 3778, 14862, 16, 203, 3639, 1731, 8526, 3778, 745, 13178, 16, 203, 3639, 533, 3778, 2477, 203, 565, 262, 3903, 288, 203, 203, 3639, 2583, 12, 11420, 1290, 626, 22536, 63, 12918, 52, 548, 8009, 2327, 422, 534, 30246, 1482, 18, 3190, 16, 315, 12918, 52, 353, 486, 1696, 364, 22071, 8863, 203, 203, 3639, 2592, 3951, 3778, 8515, 31, 203, 203, 3639, 2254, 5034, 783, 1676, 1380, 273, 8515, 1380, 31, 203, 3639, 8515, 1380, 9904, 31, 203, 203, 3639, 8515, 18, 12918, 52, 548, 273, 534, 30246, 548, 31, 203, 3639, 8515, 18, 12684, 3291, 273, 8515, 3291, 31, 203, 3639, 8515, 18, 2327, 273, 534, 30246, 17865, 1482, 18, 31575, 31, 203, 3639, 8515, 18, 11358, 273, 5774, 31, 203, 3639, 8515, 18, 2372, 273, 924, 31, 203, 3639, 8515, 18, 30730, 273, 14862, 31, 203, 3639, 8515, 18, 1991, 13178, 273, 745, 13178, 31, 203, 3639, 8515, 18, 3384, 273, 2477, 31, 203, 203, 3639, 22071, 63, 12918, 52, 548, 6362, 2972, 1676, 1380, 65, 273, 8515, 31, 203, 203, 3639, 3626, 2592, 3951, 6119, 12, 3576, 18, 15330, 16, 534, 30246, 548, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./SafeDecimalMath.sol"; import "./SelfDestructible.sol"; // AggregatorInterface from Chainlink represents a decentralized pricing network for a single currency key import "chainlink/contracts/interfaces/AggregatorInterface.sol"; /** * @title The repository for exchange rates */ contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) currentRoundForRate; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) public /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity). * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit ) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey The currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = getRateAndTimestampAtRound(currencyKey, roundId + 1); // if there's no new round, then the previous roundId was the latest if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { if (aggregators[currencyKey] != address(0)) { AggregatorInterface aggregator = aggregators[currencyKey]; return aggregator.latestRound(); } else { return currentRoundForRate[currencyKey]; } } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); } function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return getRateAndTimestampAtRound(currencyKey, roundId); } /* ========== VIEWS ========== */ /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 currencyKey) public view returns (uint256) { return getRateAndUpdatedTime(currencyKey).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(getRate(sourceCurrencyKey)).divideDecimalRound( getRate(destinationCurrencyKey) ); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return getRateAndUpdatedTime(currencyKey).rate; } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = getRate(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) external view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== INTERNAL FUNCTIONS ========== */ function _setRate(bytes32 currencyKey, uint256 rate, uint256 time) internal { // Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = getRate(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime) { if (aggregators[currencyKey] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[currencyKey].latestAnswer() * 1e10), time: uint40(aggregators[currencyKey].latestTimestamp()) }); } else { return _rates[currencyKey][currentRoundForRate[currencyKey]]; } } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } function getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { if (aggregators[currencyKey] != address(0)) { AggregatorInterface aggregator = aggregators[currencyKey]; return (uint(aggregator.getAnswer(roundId) * 1e10), aggregator.getTimestamp(roundId)); } else { RateAndUpdatedTime storage update = _rates[currencyKey][roundId]; return (update.rate, update.time); } } function getRate(bytes32 currencyKey) internal view returns (uint256) { return getRateAndUpdatedTime(currencyKey).rate; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
* @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period./ Loop through each key and check whether the data point is stale. sUSD is a special case and is never false
function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { uint256 i = 0; while (i < currencyKeys.length) { if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; }
914,263
[ 1, 1564, 309, 1281, 434, 326, 5462, 17544, 2275, 316, 15032, 1404, 2118, 3526, 364, 7144, 2353, 326, 14067, 3879, 18, 19, 9720, 3059, 1517, 498, 471, 866, 2856, 326, 501, 1634, 353, 14067, 18, 272, 3378, 40, 353, 279, 4582, 648, 471, 353, 5903, 629, 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, 1281, 4727, 2520, 19155, 12, 3890, 1578, 8526, 5462, 2396, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 277, 273, 374, 31, 203, 203, 3639, 1323, 261, 77, 411, 5462, 2396, 18, 2469, 13, 288, 203, 5411, 309, 261, 7095, 2396, 63, 77, 65, 480, 315, 87, 3378, 40, 6, 597, 1142, 4727, 1891, 10694, 12, 7095, 2396, 63, 77, 65, 2934, 1289, 12, 5141, 19155, 5027, 13, 411, 2037, 13, 288, 203, 7734, 327, 638, 31, 203, 5411, 289, 203, 5411, 277, 1011, 404, 31, 203, 3639, 289, 203, 203, 3639, 327, 629, 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 ]
./full_match/5/0x844b4F92B52cA527d716BF9d7eFd54b25f6448B8/sources/contracts/Sahayog.sol
payable indicates we'll be able to send cryptocurrency through func
function donateToCampaign(uint256 _id) public payable { uint256 amount =msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); if(sent){ campaign.amountCollected = campaign.amountCollected + amount; } }
1,921,210
[ 1, 10239, 429, 8527, 732, 5614, 506, 7752, 358, 1366, 13231, 504, 295, 3040, 3059, 1326, 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, 2727, 340, 774, 13432, 12, 11890, 5034, 389, 350, 13, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 3844, 273, 3576, 18, 1132, 31, 203, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 67, 350, 15533, 203, 203, 3639, 8965, 18, 19752, 3062, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 8965, 18, 19752, 1012, 18, 6206, 12, 8949, 1769, 203, 203, 203, 3639, 309, 12, 7569, 15329, 203, 5411, 8965, 18, 8949, 10808, 329, 273, 8965, 18, 8949, 10808, 329, 397, 3844, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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 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 <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 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.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
pool data view functions min return calculation functions state modifying functions
interface IMetaSwap { function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); }
970,285
[ 1, 6011, 501, 1476, 4186, 1131, 327, 11096, 4186, 919, 21920, 4186, 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, 5831, 467, 2781, 12521, 288, 203, 565, 445, 4506, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 9162, 12, 11890, 28, 770, 13, 3903, 1476, 1135, 261, 45, 654, 39, 3462, 1769, 203, 203, 565, 445, 9162, 1016, 12, 2867, 1147, 1887, 13, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 565, 445, 9162, 13937, 12, 11890, 28, 770, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 336, 6466, 5147, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 353, 6099, 17212, 1435, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 4604, 12521, 12, 203, 3639, 2254, 28, 1147, 1016, 1265, 16, 203, 3639, 2254, 28, 1147, 1016, 774, 16, 203, 3639, 2254, 5034, 6633, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4604, 12521, 14655, 6291, 12, 203, 3639, 2254, 28, 1147, 1016, 1265, 16, 203, 3639, 2254, 28, 1147, 1016, 774, 16, 203, 3639, 2254, 5034, 6633, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4604, 1345, 6275, 12, 11890, 5034, 8526, 745, 892, 30980, 16, 1426, 443, 1724, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4604, 3288, 48, 18988, 24237, 12, 11890, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 4604, 3288, 48, 18988, 24237, 3335, 1345, 12, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ /** ▄▄▄▄▄ ██ █▄▄▄▄ ▄█▄ ████▄ █ ▄▄ ▄ █ ██ ▄▀ ▄ ▄▄▄▄▄ █ ▀▄ █ █ █ ▄▀ █▀ ▀▄ █ █ █ █ █ █ █ █ ▄▀ █ █ ▀▄ ▄ ▀▀▀▀▄ █▄▄█ █▀▀▌ █ ▀ █ █ █▀▀▀ ██▀▀█ █▄▄█ █ ▀▄ █ █ ▄ ▀▀▀▀▄ ▀▄▄▄▄▀ █ █ █ █ █▄ ▄▀ ▀████ █ █ █ █ █ █ █ █ █ ▀▄▄▄▄▀ █ █ ▀███▀ █ █ █ ███ █▄ ▄█ █ ▀ ▀ ▀ █ ▀▀▀ ▀ ▀ */ // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts/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); } // File: contracts/libraries/Events.sol pragma solidity ^0.8.0; /** * @title A collection of Events * @notice This library defines all of the Events that the Sarcophagus system * emits */ library Events { event Creation(address sarcophagusContract); event RegisterArchaeologist( address indexed archaeologist, bytes currentPublicKey, string endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 bond ); event UpdateArchaeologist( address indexed archaeologist, string endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 addedBond ); event UpdateArchaeologistPublicKey( address indexed archaeologist, bytes currentPublicKey ); event WithdrawalFreeBond( address indexed archaeologist, uint256 withdrawnBond ); event CreateSarcophagus( bytes32 indexed identifier, address indexed archaeologist, bytes archaeologistPublicKey, address embalmer, string name, uint256 resurrectionTime, uint256 resurrectionWindow, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes recipientPublicKey, uint256 cursedBond ); event UpdateSarcophagus(bytes32 indexed identifier, string assetId); event CancelSarcophagus(bytes32 indexed identifier); event RewrapSarcophagus( string assetId, bytes32 indexed identifier, uint256 resurrectionTime, uint256 resurrectionWindow, uint256 diggingFee, uint256 bounty, uint256 cursedBond ); event UnwrapSarcophagus( string assetId, bytes32 indexed identifier, bytes32 privatekey ); event AccuseArchaeologist( bytes32 indexed identifier, address indexed accuser, uint256 accuserBondReward, uint256 embalmerBondReward ); event BurySarcophagus(bytes32 indexed identifier); event CleanUpSarcophagus( bytes32 indexed identifier, address indexed cleaner, uint256 cleanerBondReward, uint256 embalmerBondReward ); } // File: contracts/libraries/Types.sol pragma solidity ^0.8.0; /** * @title A collection of defined structs * @notice This library defines the various data models that the Sarcophagus * system uses */ library Types { struct Archaeologist { bool exists; bytes currentPublicKey; string endpoint; address paymentAddress; uint256 feePerByte; uint256 minimumBounty; uint256 minimumDiggingFee; uint256 maximumResurrectionTime; uint256 freeBond; uint256 cursedBond; } enum SarcophagusStates {DoesNotExist, Exists, Done} struct Sarcophagus { SarcophagusStates state; address archaeologist; bytes archaeologistPublicKey; address embalmer; string name; uint256 resurrectionTime; uint256 resurrectionWindow; string assetId; bytes recipientPublicKey; uint256 storageFee; uint256 diggingFee; uint256 bounty; uint256 currentCursedBond; bytes32 privateKey; } } // File: contracts/libraries/Datas.sol pragma solidity ^0.8.0; /** * @title A library implementing data structures for the Sarcophagus system * @notice This library defines a Data struct, which defines all of the state * that the Sarcophagus system needs to operate. It's expected that a single * instance of this state will exist. */ library Datas { struct Data { // archaeologists address[] archaeologistAddresses; mapping(address => Types.Archaeologist) archaeologists; // archaeologist stats mapping(address => bytes32[]) archaeologistSuccesses; mapping(address => bytes32[]) archaeologistCancels; mapping(address => bytes32[]) archaeologistAccusals; mapping(address => bytes32[]) archaeologistCleanups; // archaeologist key control mapping(bytes => bool) archaeologistUsedKeys; // sarcophaguses bytes32[] sarcophagusIdentifiers; mapping(bytes32 => Types.Sarcophagus) sarcophaguses; // sarcophagus ownerships mapping(address => bytes32[]) embalmerSarcophaguses; mapping(address => bytes32[]) archaeologistSarcophaguses; mapping(address => bytes32[]) recipientSarcophaguses; } } // File: contracts/libraries/Utils.sol pragma solidity ^0.8.0; /** * @title Utility functions used within the Sarcophagus system * @notice This library implements various functions that are used throughout * Sarcophagus, mainly to DRY up the codebase * @dev these functions are all stateless, public, pure/view */ library Utils { /** * @notice Reverts if the public key length is not exactly 64 bytes long * @param publicKey the key to check length of */ function publicKeyLength(bytes memory publicKey) public pure { require(publicKey.length == 64, "public key must be 64 bytes"); } /** * @notice Reverts if the hash of singleHash does not equal doubleHash * @param doubleHash the hash to compare hash of singleHash to * @param singleHash the value to hash and compare against doubleHash */ function hashCheck(bytes32 doubleHash, bytes memory singleHash) public pure { require(doubleHash == keccak256(singleHash), "hashes do not match"); } /** * @notice Reverts if the input string is not empty * @param assetId the string to check */ function confirmAssetIdNotSet(string memory assetId) public pure { require(bytes(assetId).length == 0, "assetId has already been set"); } /** * @notice Reverts if existing assetId is not empty, or if new assetId is * @param existingAssetId the orignal assetId to check, make sure is empty * @param newAssetId the new assetId, which must not be empty */ function assetIdsCheck( string memory existingAssetId, string memory newAssetId ) public pure { // verify that the existingAssetId is currently empty confirmAssetIdNotSet(existingAssetId); require(bytes(newAssetId).length > 0, "assetId must not have 0 length"); } /** * @notice Reverts if the given data and signature did not come from the * given address * @param data the payload which has been signed * @param v signature element * @param r signature element * @param s signature element * @param account address to confirm data and signature came from */ function signatureCheck( bytes memory data, uint8 v, bytes32 r, bytes32 s, address account ) public pure { // generate the address for a given data and signature address hopefulAddress = ecrecover(keccak256(data), v, r, s); require( hopefulAddress == account, "signature did not come from correct account" ); } /** * @notice Reverts if the given resurrection time is not in the future * @param resurrectionTime the time to check against block.timestamp */ function resurrectionInFuture(uint256 resurrectionTime) public view { require( resurrectionTime > block.timestamp, "resurrection time must be in the future" ); } /** * @notice Calculates the grace period that an archaeologist has after a * sarcophagus has reached its resurrection time * @param resurrectionTime the resurrection timestamp of a sarcophagus * @return the grace period * @dev The grace period is dependent on how far out the resurrection time * is. The longer out the resurrection time, the longer the grace period. * There is a minimum grace period of 30 minutes, otherwise, it's * calculated as 1% of the time between now and resurrection time. */ function getGracePeriod(uint256 resurrectionTime) public view returns (uint256) { // set a minimum window of 30 minutes uint16 minimumResurrectionWindow = 30 minutes; // calculate 1% of the relative time between now and the resurrection // time uint256 gracePeriod = (resurrectionTime - block.timestamp) / 100; // if our calculated grace period is less than the minimum time, we'll // use the minimum time instead if (gracePeriod < minimumResurrectionWindow) { gracePeriod = minimumResurrectionWindow; } // return that grace period return gracePeriod; } /** * @notice Reverts if we're not within the resurrection window (on either * side) * @param resurrectionTime the resurrection time of the sarcophagus * (absolute, i.e. a date time stamp) * @param resurrectionWindow the resurrection window of the sarcophagus * (relative, i.e. "30 minutes") */ function unwrapTime(uint256 resurrectionTime, uint256 resurrectionWindow) public view { // revert if too early require( resurrectionTime <= block.timestamp, "it's not time to unwrap the sarcophagus" ); // revert if too late require( resurrectionTime + resurrectionWindow >= block.timestamp, "the resurrection window has expired" ); } /** * @notice Reverts if msg.sender is not equal to passed-in address * @param account the account to verify is msg.sender */ function sarcophagusUpdater(address account) public view { require( account == msg.sender, "sarcophagus cannot be updated by account" ); } /** * @notice Reverts if the input resurrection time, digging fee, or bounty * don't fit within the other given maximum and minimum values * @param resurrectionTime the resurrection time to check * @param diggingFee the digging fee to check * @param bounty the bounty to check * @param maximumResurrectionTime the maximum resurrection time to check * against, in relative terms (i.e. "1 year" is 31536000 (seconds)) * @param minimumDiggingFee the minimum digging fee to check against * @param minimumBounty the minimum bounty to check against */ function withinArchaeologistLimits( uint256 resurrectionTime, uint256 diggingFee, uint256 bounty, uint256 maximumResurrectionTime, uint256 minimumDiggingFee, uint256 minimumBounty ) public view { // revert if the given resurrection time is too far in the future require( resurrectionTime <= block.timestamp + maximumResurrectionTime, "resurrection time too far in the future" ); // revert if the given digging fee is too low require(diggingFee >= minimumDiggingFee, "digging fee is too low"); // revert if the given bounty is too low require(bounty >= minimumBounty, "bounty is too low"); } } // File: contracts/libraries/Archaeologists.sol pragma solidity ^0.8.0; /** * @title A library implementing Archaeologist-specific logic in the * Sarcophagus system * @notice This library includes public functions for manipulating * archaeologists in the Sarcophagus system */ library Archaeologists { /** * @notice Checks that an archaeologist exists, or doesn't exist, and * and reverts if necessary * @param data the system's data struct instance * @param account the archaeologist address to check existence of * @param exists bool which flips whether function reverts if archaeologist * exists or not */ function archaeologistExists( Datas.Data storage data, address account, bool exists ) public view { // set the error message string memory err = "archaeologist has not been registered yet"; if (!exists) err = "archaeologist has already been registered"; // revert if necessary require(data.archaeologists[account].exists == exists, err); } /** * @notice Increases internal data structure which tracks free bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase free bond by */ function increaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // increase the freeBond variable by amount arch.freeBond = arch.freeBond + amount; } /** * @notice Decreases internal data structure which tracks free bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease free bond by */ function decreaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // decrease the free bond variable by amount, reverting if necessary require( arch.freeBond >= amount, "archaeologist does not have enough free bond" ); arch.freeBond = arch.freeBond - amount; } /** * @notice Increases internal data structure which tracks cursed bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase cursed bond by */ function increaseCursedBond( Datas.Data storage data, address archAddress, uint256 amount ) private { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // increase the freeBond variable by amount arch.cursedBond = arch.cursedBond + amount; } /** * @notice Decreases internal data structure which tracks cursed bond per * archaeologist * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease cursed bond by */ function decreaseCursedBond( Datas.Data storage data, address archAddress, uint256 amount ) public { // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[archAddress]; // decrease the free bond variable by amount arch.cursedBond = arch.cursedBond - amount; } /** * @notice Given an archaeologist and amount, decrease free bond and * increase cursed bond * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to decrease free bond and increase cursed bond */ function lockUpBond( Datas.Data storage data, address archAddress, uint256 amount ) public { decreaseFreeBond(data, archAddress, amount); increaseCursedBond(data, archAddress, amount); } /** * @notice Given an archaeologist and amount, increase free bond and * decrease cursed bond * @param data the system's data struct instance * @param archAddress the archaeologist's address to operate on * @param amount the amount to increase free bond and decrease cursed bond */ function freeUpBond( Datas.Data storage data, address archAddress, uint256 amount ) public { increaseFreeBond(data, archAddress, amount); decreaseCursedBond(data, archAddress, amount); } /** * @notice Calculates and returns the curse for any sarcophagus * @param diggingFee the digging fee of a sarcophagus * @param bounty the bounty of a sarcophagus * @return amount of the curse * @dev Current implementation simply adds the two inputs together. Future * strategies should use historical data to build a curve to change this * amount over time. */ function getCursedBond(uint256 diggingFee, uint256 bounty) public pure returns (uint256) { // TODO: implment a better algorithm, using some concept of past state return diggingFee + bounty; } /** * @notice Registers a new archaeologist in the system * @param data the system's data struct instance * @param currentPublicKey the public key to be used in the first * sarcophagus * @param endpoint where to contact this archaeologist on the internet * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to start with * @param sarcoToken the SARCO token used for payment handling * @return index of the new archaeologist */ function registerArchaeologist( Datas.Data storage data, bytes memory currentPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond, IERC20 sarcoToken ) public returns (uint256) { // verify that the archaeologist does not already exist archaeologistExists(data, msg.sender, false); // verify that the public key length is accurate Utils.publicKeyLength(currentPublicKey); // transfer SARCO tokens from the archaeologist to this contract, to be // used as their free bond. can be 0, which indicates that the // archaeologist is not eligible for any new jobs if (freeBond > 0) { sarcoToken.transferFrom(msg.sender, address(this), freeBond); } // create a new archaeologist Types.Archaeologist memory newArch = Types.Archaeologist({ exists: true, currentPublicKey: currentPublicKey, endpoint: endpoint, paymentAddress: paymentAddress, feePerByte: feePerByte, minimumBounty: minimumBounty, minimumDiggingFee: minimumDiggingFee, maximumResurrectionTime: maximumResurrectionTime, freeBond: freeBond, cursedBond: 0 }); // save the new archaeologist into relevant data structures data.archaeologists[msg.sender] = newArch; data.archaeologistAddresses.push(msg.sender); // emit an event emit Events.RegisterArchaeologist( msg.sender, newArch.currentPublicKey, newArch.endpoint, newArch.paymentAddress, newArch.feePerByte, newArch.minimumBounty, newArch.minimumDiggingFee, newArch.maximumResurrectionTime, newArch.freeBond ); // return index of the new archaeologist return data.archaeologistAddresses.length - 1; } /** * @notice An archaeologist may update their profile * @param data the system's data struct instance * @param endpoint where to contact this archaeologist on the internet * @param newPublicKey the public key to be used in the next * sarcophagus * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to add to their profile * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the update was successful */ function updateArchaeologist( Datas.Data storage data, bytes memory newPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond, IERC20 sarcoToken ) public returns (bool) { // verify that the archaeologist exists, and is the sender of this // transaction archaeologistExists(data, msg.sender, true); // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[msg.sender]; // if archaeologist is updating their active public key, emit an event if (keccak256(arch.currentPublicKey) != keccak256(newPublicKey)) { emit Events.UpdateArchaeologistPublicKey(msg.sender, newPublicKey); arch.currentPublicKey = newPublicKey; } // update the rest of the archaeologist profile arch.endpoint = endpoint; arch.paymentAddress = paymentAddress; arch.feePerByte = feePerByte; arch.minimumBounty = minimumBounty; arch.minimumDiggingFee = minimumDiggingFee; arch.maximumResurrectionTime = maximumResurrectionTime; // the freeBond variable acts as an incrementer, so only if it's above // zero will we update their profile variable and transfer the tokens if (freeBond > 0) { increaseFreeBond(data, msg.sender, freeBond); sarcoToken.transferFrom(msg.sender, address(this), freeBond); } // emit an event emit Events.UpdateArchaeologist( msg.sender, arch.endpoint, arch.paymentAddress, arch.feePerByte, arch.minimumBounty, arch.minimumDiggingFee, arch.maximumResurrectionTime, freeBond ); // return true return true; } /** * @notice Archaeologist can withdraw any of their free bond * @param data the system's data struct instance * @param amount the amount of the archaeologist's free bond that they're * withdrawing * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the withdrawal was successful */ function withdrawBond( Datas.Data storage data, uint256 amount, IERC20 sarcoToken ) public returns (bool) { // verify that the archaeologist exists, and is the sender of this // transaction archaeologistExists(data, msg.sender, true); // move free bond out of the archaeologist decreaseFreeBond(data, msg.sender, amount); // transfer the freed SARCOs back to the archaeologist sarcoToken.transfer(msg.sender, amount); // emit event emit Events.WithdrawalFreeBond(msg.sender, amount); // return true return true; } } // File: contracts/libraries/PrivateKeys.sol pragma solidity ^0.8.0; /** * @title Private key verification * @notice Implements a private key -> public key checking function * @dev modified from https://github.com/1Address/ecsol, removes extra code * which isn't necessary for our Sarcophagus implementation */ library PrivateKeys { uint256 public constant gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 public constant gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // // Based on the original idea of Vitalik Buterin: // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // function ecmulVerify( uint256 x1, uint256 y1, bytes32 scalar, bytes memory pubKey ) private pure returns (bool) { uint256 m = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover( 0, y1 % 2 != 0 ? 28 : 27, bytes32(x1), bytes32(mulmod(uint256(scalar), x1, m)) ); address xyAddress = address( uint160( uint256(keccak256(pubKey)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) ); return xyAddress == signer; } /** * @notice Given a private key and a public key, determines if that public * key was derived from the private key * @param privKey an secp256k1 private key * @param pubKey an secp256k1 public key * @return bool indicating whether the public key is derived from the * private key */ function keyVerification(bytes32 privKey, bytes memory pubKey) public pure returns (bool) { return ecmulVerify(gx, gy, privKey, pubKey); } } // File: contracts/libraries/Sarcophaguses.sol pragma solidity ^0.8.0; /** * @title A library implementing Sarcophagus-specific logic in the * Sarcophagus system * @notice This library includes public functions for manipulating * sarcophagi in the Sarcophagus system */ library Sarcophaguses { /** * @notice Reverts if the given sarcState does not equal the comparison * state * @param sarcState the state of a sarcophagus * @param state the state to compare to */ function sarcophagusState( Types.SarcophagusStates sarcState, Types.SarcophagusStates state ) internal pure { // set the error message string memory error = "sarcophagus already exists"; if (state == Types.SarcophagusStates.Exists) error = "sarcophagus does not exist or is not active"; // revert if states are not equal require(sarcState == state, error); } /** * @notice Takes a sarcophagus's cursed bond, splits it in half, and sends * to the transaction caller and embalmer * @param data the system's data struct instance * @param paymentAddress payment address for the transaction caller * @param sarc the sarcophagus to operate on * @param sarcoToken the SARCO token used for payment handling * @return halfToSender the amount of SARCO token going to transaction * sender * @return halfToEmbalmer the amount of SARCO token going to embalmer */ function splitSend( Datas.Data storage data, address paymentAddress, Types.Sarcophagus storage sarc, IERC20 sarcoToken ) private returns (uint256, uint256) { // split the sarcophagus's cursed bond into two halves, taking into // account solidity math uint256 halfToEmbalmer = sarc.currentCursedBond / 2; uint256 halfToSender = sarc.currentCursedBond - halfToEmbalmer; // transfer the cursed half, plus bounty, plus digging fee to the // embalmer sarcoToken.transfer( sarc.embalmer, sarc.bounty + sarc.diggingFee + halfToEmbalmer ); // transfer the other half of the cursed bond to the transaction caller sarcoToken.transfer(paymentAddress, halfToSender); // update (decrease) the archaeologist's cursed bond, because this // sarcophagus is over Archaeologists.decreaseCursedBond( data, sarc.archaeologist, sarc.currentCursedBond ); // return data return (halfToSender, halfToEmbalmer); } /** * @notice Embalmer creates the skeleton for a new sarcopahgus * @param data the system's data struct instance * @param name the name of the sarcophagus * @param archaeologist the address of a registered archaeologist to * assign this sarcophagus to * @param resurrectionTime the resurrection time of the sarcophagus * @param storageFee the storage fee that the archaeologist will receive, * for saving this sarcophagus on Arweave * @param diggingFee the digging fee that the archaeologist will receive at * the first rewrap * @param bounty the bounty that the archaeologist will receive when the * sarcophagus is unwrapped * @param identifier the identifier of the sarcophagus, which is the hash * of the hash of the inner encrypted layer of the sarcophagus * @param recipientPublicKey the public key of the recipient * @param sarcoToken the SARCO token used for payment handling * @return index of the new sarcophagus */ function createSarcophagus( Datas.Data storage data, string memory name, address archaeologist, uint256 resurrectionTime, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes32 identifier, bytes memory recipientPublicKey, IERC20 sarcoToken ) public returns (uint256) { // confirm that the archaeologist exists Archaeologists.archaeologistExists(data, archaeologist, true); // confirm that the public key length is correct Utils.publicKeyLength(recipientPublicKey); // confirm that this exact sarcophagus does not yet exist sarcophagusState( data.sarcophaguses[identifier].state, Types.SarcophagusStates.DoesNotExist ); // confirm that the resurrection time is in the future Utils.resurrectionInFuture(resurrectionTime); // load the archaeologist Types.Archaeologist memory arch = data.archaeologists[archaeologist]; // check that the new sarcophagus parameters fit within the selected // archaeologist's parameters Utils.withinArchaeologistLimits( resurrectionTime, diggingFee, bounty, arch.maximumResurrectionTime, arch.minimumDiggingFee, arch.minimumBounty ); // calculate the amount of archaeologist's bond to lock up uint256 cursedBondAmount = Archaeologists.getCursedBond(diggingFee, bounty); // lock up that bond Archaeologists.lockUpBond(data, archaeologist, cursedBondAmount); // create a new sarcophagus Types.Sarcophagus memory sarc = Types.Sarcophagus({ state: Types.SarcophagusStates.Exists, archaeologist: archaeologist, archaeologistPublicKey: arch.currentPublicKey, embalmer: msg.sender, name: name, resurrectionTime: resurrectionTime, resurrectionWindow: Utils.getGracePeriod(resurrectionTime), assetId: "", recipientPublicKey: recipientPublicKey, storageFee: storageFee, diggingFee: diggingFee, bounty: bounty, currentCursedBond: cursedBondAmount, privateKey: 0 }); // derive the recipient's address from their public key address recipientAddress = address(uint160(uint256(keccak256(recipientPublicKey)))); // save the sarcophagus into necessary data structures data.sarcophaguses[identifier] = sarc; data.sarcophagusIdentifiers.push(identifier); data.embalmerSarcophaguses[msg.sender].push(identifier); data.archaeologistSarcophaguses[archaeologist].push(identifier); data.recipientSarcophaguses[recipientAddress].push(identifier); // transfer digging fee + bounty + storage fee from embalmer to this // contract sarcoToken.transferFrom( msg.sender, address(this), diggingFee + bounty + storageFee ); // emit event with all the data emit Events.CreateSarcophagus( identifier, sarc.archaeologist, sarc.archaeologistPublicKey, sarc.embalmer, sarc.name, sarc.resurrectionTime, sarc.resurrectionWindow, sarc.storageFee, sarc.diggingFee, sarc.bounty, sarc.recipientPublicKey, sarc.currentCursedBond ); // return index of the new sarcophagus return data.sarcophagusIdentifiers.length - 1; } /** * @notice Embalmer updates a sarcophagus given it's identifier, after * the archaeologist has uploaded the encrypted payload onto Arweave * @param data the system's data struct instance * @param newPublicKey the archaeologist's new public key, to use for * encrypting the next sarcophagus that they're assigned to * @param identifier the identifier of the sarcophagus * @param assetId the identifier of the encrypted asset on Arweave * @param v signature element * @param r signature element * @param s signature element * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the update was successful */ function updateSarcophagus( Datas.Data storage data, bytes memory newPublicKey, bytes32 identifier, string memory assetId, uint8 v, bytes32 r, bytes32 s, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that the sarcophagus does not currently have an assetId, and // that we are setting an actual assetId Utils.assetIdsCheck(sarc.assetId, assetId); // verify that the archaeologist's new public key, and the assetId, // actually came from the archaeologist and were not tampered Utils.signatureCheck( abi.encodePacked(newPublicKey, assetId), v, r, s, sarc.archaeologist ); // revert if the new public key coming from the archaeologist has // already been used require( !data.archaeologistUsedKeys[sarc.archaeologistPublicKey], "public key already used" ); // make sure that the new public key can't be used again in the future data.archaeologistUsedKeys[sarc.archaeologistPublicKey] = true; // set the assetId on the sarcophagus sarc.assetId = assetId; // load up the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // set the new public key on the archaeologist arch.currentPublicKey = newPublicKey; // transfer the storage fee to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.storageFee); sarc.storageFee = 0; // emit some events emit Events.UpdateSarcophagus(identifier, assetId); emit Events.UpdateArchaeologistPublicKey( sarc.archaeologist, arch.currentPublicKey ); // return true return true; } /** * @notice An embalmer may cancel a sarcophagus if it hasn't been * completely created * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the cancel was successful */ function cancelSarcophagus( Datas.Data storage data, bytes32 identifier, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the asset id has not yet been set Utils.confirmAssetIdNotSet(sarc.assetId); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // transfer the bounty and storage fee back to the embalmer sarcoToken.transfer(sarc.embalmer, sarc.bounty + sarc.storageFee); // load the archaeologist Types.Archaeologist memory arch = data.archaeologists[sarc.archaeologist]; // transfer the digging fee over to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // free up the cursed bond on the archaeologist, because this // sarcophagus is over Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // set the sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // save the fact that this sarcophagus has been cancelled, against the // archaeologist data.archaeologistCancels[sarc.archaeologist].push(identifier); // emit an event emit Events.CancelSarcophagus(identifier); // return true return true; } /** * @notice Embalmer can extend the resurrection time of the sarcophagus, * as long as the previous resurrection time is in the future * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param resurrectionTime new resurrection time for the rewrapped * sarcophagus * @param diggingFee new digging fee for the rewrapped sarcophagus * @param bounty new bounty for the rewrapped sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the rewrap was successful */ function rewrapSarcophagus( Datas.Data storage data, bytes32 identifier, uint256 resurrectionTime, uint256 diggingFee, uint256 bounty, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer is making this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that both the current resurrection time, and the new // resurrection time, are in the future Utils.resurrectionInFuture(sarc.resurrectionTime); Utils.resurrectionInFuture(resurrectionTime); // load the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // check that the sarcophagus updated parameters fit within the // archaeologist's parameters Utils.withinArchaeologistLimits( resurrectionTime, diggingFee, bounty, arch.maximumResurrectionTime, arch.minimumDiggingFee, arch.minimumBounty ); // transfer the new digging fee from embalmer to this contract sarcoToken.transferFrom(msg.sender, address(this), diggingFee); // transfer the old digging fee to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // calculate the amount of archaeologist's bond to lock up uint256 cursedBondAmount = Archaeologists.getCursedBond(diggingFee, bounty); // if new cursed bond amount is greater than current cursed bond // amount, calculate difference and lock it up. if it's less than, // calculate difference and free it up. if (cursedBondAmount > sarc.currentCursedBond) { uint256 diff = cursedBondAmount - sarc.currentCursedBond; Archaeologists.lockUpBond(data, sarc.archaeologist, diff); } else if (cursedBondAmount < sarc.currentCursedBond) { uint256 diff = sarc.currentCursedBond - cursedBondAmount; Archaeologists.freeUpBond(data, sarc.archaeologist, diff); } // determine the new grace period for the archaeologist's final proof uint256 gracePeriod = Utils.getGracePeriod(resurrectionTime); // set variarbles on the sarcopahgus sarc.resurrectionTime = resurrectionTime; sarc.diggingFee = diggingFee; sarc.bounty = bounty; sarc.currentCursedBond = cursedBondAmount; sarc.resurrectionWindow = gracePeriod; // emit an event emit Events.RewrapSarcophagus( sarc.assetId, identifier, resurrectionTime, gracePeriod, diggingFee, bounty, cursedBondAmount ); // return true return true; } /** * @notice Given a sarcophagus identifier, preimage, and private key, * verify that the data is valid and close out that sarcophagus * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param privateKey the archaeologist's private key which will decrypt the * @param sarcoToken the SARCO token used for payment handling * outer layer of the encrypted payload on Arweave * @return bool indicating that the unwrap was successful */ function unwrapSarcophagus( Datas.Data storage data, bytes32 identifier, bytes32 privateKey, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that we're in the resurrection window Utils.unwrapTime(sarc.resurrectionTime, sarc.resurrectionWindow); // verify that the given private key derives the public key on the // sarcophagus require( PrivateKeys.keyVerification( privateKey, sarc.archaeologistPublicKey ), "!privateKey" ); // save that private key onto the sarcophagus model sarc.privateKey = privateKey; // load up the archaeologist Types.Archaeologist memory arch = data.archaeologists[sarc.archaeologist]; // transfer the Digging fee and bounty over to the archaeologist sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee + sarc.bounty); // free up the archaeologist's cursed bond, because this sarcophagus is // done Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // set the sarcophagus to Done sarc.state = Types.SarcophagusStates.Done; // save this successful sarcophagus against the archaeologist data.archaeologistSuccesses[sarc.archaeologist].push(identifier); // emit an event emit Events.UnwrapSarcophagus(sarc.assetId, identifier, privateKey); // return true return true; } /** * @notice Given a sarcophagus, accuse the archaeologist for unwrapping the * sarcophagus early * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param singleHash the preimage of the sarcophagus identifier * @param paymentAddress the address to receive payment for accusing the * archaeologist * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the accusal was successful */ function accuseArchaeologist( Datas.Data storage data, bytes32 identifier, bytes memory singleHash, address paymentAddress, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the resurrection time is in the future Utils.resurrectionInFuture(sarc.resurrectionTime); // verify that the accuser has data which proves that the archaeologist // released the payload too early Utils.hashCheck(identifier, singleHash); // reward this transaction's caller, and the embalmer, with the cursed // bond, and refund the rest of the payment (bounty and digging fees) // back to the embalmer (uint256 halfToSender, uint256 halfToEmbalmer) = splitSend(data, paymentAddress, sarc, sarcoToken); // save the accusal against the archaeologist data.archaeologistAccusals[sarc.archaeologist].push(identifier); // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.AccuseArchaeologist( identifier, msg.sender, halfToSender, halfToEmbalmer ); // return true return true; } /** * @notice Extends a sarcophagus resurrection time into infinity * effectively signaling that the sarcophagus is over and should never be * resurrected * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the bury was successful */ function burySarcophagus( Datas.Data storage data, bytes32 identifier, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the embalmer made this transaction Utils.sarcophagusUpdater(sarc.embalmer); // verify that the existing resurrection time is in the future Utils.resurrectionInFuture(sarc.resurrectionTime); // load the archaeologist Types.Archaeologist storage arch = data.archaeologists[sarc.archaeologist]; // free the archaeologist's bond, because this sarcophagus is over Archaeologists.freeUpBond( data, sarc.archaeologist, sarc.currentCursedBond ); // transfer the digging fee to the archae sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee); // set the resurrection time of this sarcopahgus at maxint sarc.resurrectionTime = 2**256 - 1; // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.BurySarcophagus(identifier); // return true return true; } /** * @notice Clean up a sarcophagus whose resurrection time and window have * passed. Callable by anyone. * @param data the system's data struct instance * @param identifier the identifier of the sarcophagus * @param paymentAddress the address to receive payment for cleaning up the * sarcophagus * @param sarcoToken the SARCO token used for payment handling * @return bool indicating that the clean up was successful */ function cleanUpSarcophagus( Datas.Data storage data, bytes32 identifier, address paymentAddress, IERC20 sarcoToken ) public returns (bool) { // load the sarcophagus, and make sure it exists Types.Sarcophagus storage sarc = data.sarcophaguses[identifier]; sarcophagusState(sarc.state, Types.SarcophagusStates.Exists); // verify that the resurrection window has expired require( sarc.resurrectionTime + sarc.resurrectionWindow < block.timestamp, "sarcophagus resurrection period must be in the past" ); // reward this transaction's caller, and the embalmer, with the cursed // bond, and refund the rest of the payment (bounty and digging fees) // back to the embalmer (uint256 halfToSender, uint256 halfToEmbalmer) = splitSend(data, paymentAddress, sarc, sarcoToken); // save the cleanup against the archaeologist data.archaeologistCleanups[sarc.archaeologist].push(identifier); // update sarcophagus state to Done sarc.state = Types.SarcophagusStates.Done; // emit an event emit Events.CleanUpSarcophagus( identifier, msg.sender, halfToSender, halfToEmbalmer ); // return true return true; } } // File: contracts/Sarcophagus.sol pragma solidity ^0.8.0; /** * @title The main Sarcophagus system contract * @notice This contract implements the entire public interface for the * Sarcophagus system * * Sarcophagus implements a Dead Man's Switch using the Ethereum network as * the official source of truth for the switch (the "sarcophagus"), the Arweave * blockchain as the data storage layer for the encrypted payload, and a * decentralized network of secret-holders (the "archaeologists") who are * responsible for keeping a private key secret until the dead man's switch is * activated (via inaction by the "embalmer", the creator of the sarcophagus). * * @dev All function calls "proxy" down to functions implemented in one of * many libraries */ contract Sarcophagus is Initializable { // keep a reference to the SARCO token, which is used for payments // throughout the system IERC20 public sarcoToken; // all system data is stored within this single instance (_data) of the // Data struct Datas.Data private _data; /** * @notice Contract initializer * @param _sarcoToken The address of the SARCO token */ function initialize(address _sarcoToken) public initializer { sarcoToken = IERC20(_sarcoToken); emit Events.Creation(_sarcoToken); } /** * @notice Return the number of archaeologists that have been registered * @return total registered archaeologist count */ function archaeologistCount() public view virtual returns (uint256) { return _data.archaeologistAddresses.length; } /** * @notice Given an index (of the full archaeologist array), return the * archaeologist address at that index * @param index The index of the registered archaeologist * @return address of the archaeologist */ function archaeologistAddresses(uint256 index) public view virtual returns (address) { return _data.archaeologistAddresses[index]; } /** * @notice Given an archaeologist address, return that archaeologist's * profile * @param account The archaeologist account's address * @return the Archaeologist object */ function archaeologists(address account) public view virtual returns (Types.Archaeologist memory) { return _data.archaeologists[account]; } /** * @notice Return the total number of sarcophagi that have been created * @return the number of sarcophagi that have ever been created */ function sarcophagusCount() public view virtual returns (uint256) { return _data.sarcophagusIdentifiers.length; } /** * @notice Return the unique identifier of a sarcophagus, given it's index * @param index The index of the sarcophagus * @return the unique identifier of the given sarcophagus */ function sarcophagusIdentifier(uint256 index) public view virtual returns (bytes32) { return _data.sarcophagusIdentifiers[index]; } /** * @notice Returns the count of sarcophagi created by a specific embalmer * @param embalmer The address of the given embalmer * @return the number of sarcophagi which have been created by an embalmer */ function embalmerSarcophagusCount(address embalmer) public view virtual returns (uint256) { return _data.embalmerSarcophaguses[embalmer].length; } /** * @notice Returns the sarcophagus unique identifier for a given embalmer * and index * @param embalmer The address of an embalmer * @param index The index of the embalmer's list of sarcophagi * @return the double hash associated with the index of the embalmer's * sarcophagi */ function embalmerSarcophagusIdentifier(address embalmer, uint256 index) public view virtual returns (bytes32) { return _data.embalmerSarcophaguses[embalmer][index]; } /** * @notice Returns the count of sarcophagi created for a specific * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of sarcophagi which have been created for an * archaeologist */ function archaeologistSarcophagusCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistSarcophaguses[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's list of sarcophagi * @return the identifier associated with the index of the archaeologist's * sarcophagi */ function archaeologistSarcophagusIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistSarcophaguses[archaeologist][index]; } /** * @notice Returns the count of sarcophagi created for a specific recipient * @param recipient The address of the given recipient * @return the number of sarcophagi which have been created for a recipient */ function recipientSarcophagusCount(address recipient) public view virtual returns (uint256) { return _data.recipientSarcophaguses[recipient].length; } /** * @notice Returns the sarcophagus unique identifier for a given recipient * and index * @param recipient The address of a recipient * @param index The index of the recipient's list of sarcophagi * @return the identifier associated with the index of the recipient's * sarcophagi */ function recipientSarcophagusIdentifier(address recipient, uint256 index) public view virtual returns (bytes32) { return _data.recipientSarcophaguses[recipient][index]; } /** * @notice Returns the count of successful sarcophagi completed by the * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of sarcophagi which have been successfully completed * by the archaeologist */ function archaeologistSuccessesCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistSuccesses[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given archaeologist * and index of successful sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's list of successfully * completed sarcophagi * @return the identifier associated with the index of the archaeologist's * successfully completed sarcophagi */ function archaeologistSuccessesIdentifier( address archaeologist, uint256 index ) public view returns (bytes32) { return _data.archaeologistSuccesses[archaeologist][index]; } /** * @notice Returns the count of cancelled sarcophagi from the archaeologist * @param archaeologist The address of the given archaeologist * @return the number of cancelled sarcophagi from the archaeologist */ function archaeologistCancelsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistCancels[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given archaeologist * and index of the cancelled sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's cancelled sarcophagi * @return the identifier associated with the index of the archaeologist's * cancelled sarcophagi */ function archaeologistCancelsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistCancels[archaeologist][index]; } /** * @notice Returns the count of accused sarcophagi from the archaeologist * @param archaeologist The address of the given archaeologist * @return the number of accused sarcophagi from the archaeologist */ function archaeologistAccusalsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistAccusals[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index of the accused sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's accused sarcophagi * @return the identifier associated with the index of the archaeologist's * accused sarcophagi */ function archaeologistAccusalsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistAccusals[archaeologist][index]; } /** * @notice Returns the count of cleaned-up sarcophagi from the * archaeologist * @param archaeologist The address of the given archaeologist * @return the number of cleaned-up sarcophagi from the archaeologist */ function archaeologistCleanupsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistCleanups[archaeologist].length; } /** * @notice Returns the sarcophagus unique identifier for a given * archaeologist and index of the cleaned-up sarcophagi * @param archaeologist The address of an archaeologist * @param index The index of the archaeologist's accused sarcophagi * @return the identifier associated with the index of the archaeologist's * leaned-up sarcophagi */ function archaeologistCleanupsIdentifier( address archaeologist, uint256 index ) public view virtual returns (bytes32) { return _data.archaeologistCleanups[archaeologist][index]; } /** * @notice Returns sarcophagus data given an indentifier * @param identifier the unique identifier a sarcophagus * @return sarc the Sarcophagus object */ function sarcophagus(bytes32 identifier) public view virtual returns (Types.Sarcophagus memory) { return _data.sarcophaguses[identifier]; } /** * @notice Registers a new archaeologist in the system * @param currentPublicKey the public key to be used in the first * sarcophagus * @param endpoint where to contact this archaeologist on the internet * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to start with * @return index of the new archaeologist */ function registerArchaeologist( bytes memory currentPublicKey, string memory endpoint, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond ) public virtual returns (uint256) { return Archaeologists.registerArchaeologist( _data, currentPublicKey, endpoint, paymentAddress, feePerByte, minimumBounty, minimumDiggingFee, maximumResurrectionTime, freeBond, sarcoToken ); } /** * @notice An archaeologist may update their profile * @param endpoint where to contact this archaeologist on the internet * @param newPublicKey the public key to be used in the next * sarcophagus * @param paymentAddress all collected payments for the archaeologist will * be sent here * @param feePerByte amount of SARCO tokens charged per byte of storage * being sent to Arweave * @param minimumBounty the minimum bounty for a sarcophagus that the * archaeologist will accept * @param minimumDiggingFee the minimum digging fee for a sarcophagus that * the archaeologist will accept * @param maximumResurrectionTime the maximum resurrection time for a * sarcophagus that the archaeologist will accept, in relative terms (i.e. * "1 year" is 31536000 (seconds)) * @param freeBond the amount of SARCO bond that the archaeologist wants * to add to their profile * @return bool indicating that the update was successful */ function updateArchaeologist( string memory endpoint, bytes memory newPublicKey, address paymentAddress, uint256 feePerByte, uint256 minimumBounty, uint256 minimumDiggingFee, uint256 maximumResurrectionTime, uint256 freeBond ) public virtual returns (bool) { return Archaeologists.updateArchaeologist( _data, newPublicKey, endpoint, paymentAddress, feePerByte, minimumBounty, minimumDiggingFee, maximumResurrectionTime, freeBond, sarcoToken ); } /** * @notice Archaeologist can withdraw any of their free bond * @param amount the amount of the archaeologist's free bond that they're * withdrawing * @return bool indicating that the withdrawal was successful */ function withdrawBond(uint256 amount) public virtual returns (bool) { return Archaeologists.withdrawBond(_data, amount, sarcoToken); } /** * @notice Embalmer creates the skeleton for a new sarcopahgus * @param name the name of the sarcophagus * @param archaeologist the address of a registered archaeologist to * assign this sarcophagus to * @param resurrectionTime the resurrection time of the sarcophagus * @param storageFee the storage fee that the archaeologist will receive, * for saving this sarcophagus on Arweave * @param diggingFee the digging fee that the archaeologist will receive at * the first rewrap * @param bounty the bounty that the archaeologist will receive when the * sarcophagus is unwrapped * @param identifier the identifier of the sarcophagus, which is the hash * of the hash of the inner encrypted layer of the sarcophagus * @param recipientPublicKey the public key of the recipient * @return index of the new sarcophagus */ function createSarcophagus( string memory name, address archaeologist, uint256 resurrectionTime, uint256 storageFee, uint256 diggingFee, uint256 bounty, bytes32 identifier, bytes memory recipientPublicKey ) public virtual returns (uint256) { return Sarcophaguses.createSarcophagus( _data, name, archaeologist, resurrectionTime, storageFee, diggingFee, bounty, identifier, recipientPublicKey, sarcoToken ); } /** * @notice Embalmer updates a sarcophagus given it's identifier, after * the archaeologist has uploaded the encrypted payload onto Arweave * @param newPublicKey the archaeologist's new public key, to use for * encrypting the next sarcophagus that they're assigned to * @param identifier the identifier of the sarcophagus * @param assetId the identifier of the encrypted asset on Arweave * @param v signature element * @param r signature element * @param s signature element * @return bool indicating that the update was successful */ function updateSarcophagus( bytes memory newPublicKey, bytes32 identifier, string memory assetId, uint8 v, bytes32 r, bytes32 s ) public virtual returns (bool) { return Sarcophaguses.updateSarcophagus( _data, newPublicKey, identifier, assetId, v, r, s, sarcoToken ); } /** * @notice An embalmer may cancel a sarcophagus if it hasn't been * completely created * @param identifier the identifier of the sarcophagus * @return bool indicating that the cancel was successful */ function cancelSarcophagus(bytes32 identifier) public virtual returns (bool) { return Sarcophaguses.cancelSarcophagus(_data, identifier, sarcoToken); } /** * @notice Embalmer can extend the resurrection time of the sarcophagus, * as long as the previous resurrection time is in the future * @param identifier the identifier of the sarcophagus * @param resurrectionTime new resurrection time for the rewrapped * sarcophagus * @param diggingFee new digging fee for the rewrapped sarcophagus * @param bounty new bounty for the rewrapped sarcophagus * @return bool indicating that the rewrap was successful */ function rewrapSarcophagus( bytes32 identifier, uint256 resurrectionTime, uint256 diggingFee, uint256 bounty ) public virtual returns (bool) { return Sarcophaguses.rewrapSarcophagus( _data, identifier, resurrectionTime, diggingFee, bounty, sarcoToken ); } /** * @notice Given a sarcophagus identifier, preimage, and private key, * verify that the data is valid and close out that sarcophagus * @param identifier the identifier of the sarcophagus * @param privateKey the archaeologist's private key which will decrypt the * outer layer of the encrypted payload on Arweave * @return bool indicating that the unwrap was successful */ function unwrapSarcophagus(bytes32 identifier, bytes32 privateKey) public virtual returns (bool) { return Sarcophaguses.unwrapSarcophagus( _data, identifier, privateKey, sarcoToken ); } /** * @notice Given a sarcophagus, accuse the archaeologist for unwrapping the * sarcophagus early * @param identifier the identifier of the sarcophagus * @param singleHash the preimage of the sarcophagus identifier * @param paymentAddress the address to receive payment for accusing the * archaeologist * @return bool indicating that the accusal was successful */ function accuseArchaeologist( bytes32 identifier, bytes memory singleHash, address paymentAddress ) public virtual returns (bool) { return Sarcophaguses.accuseArchaeologist( _data, identifier, singleHash, paymentAddress, sarcoToken ); } /** * @notice Extends a sarcophagus resurrection time into infinity * effectively signaling that the sarcophagus is over and should never be * resurrected * @param identifier the identifier of the sarcophagus * @return bool indicating that the bury was successful */ function burySarcophagus(bytes32 identifier) public virtual returns (bool) { return Sarcophaguses.burySarcophagus(_data, identifier, sarcoToken); } /** * @notice Clean up a sarcophagus whose resurrection time and window have * passed. Callable by anyone. * @param identifier the identifier of the sarcophagus * @param paymentAddress the address to receive payment for cleaning up the * sarcophagus * @return bool indicating that the clean up was successful */ function cleanUpSarcophagus(bytes32 identifier, address paymentAddress) public virtual returns (bool) { return Sarcophaguses.cleanUpSarcophagus( _data, identifier, paymentAddress, sarcoToken ); } }
* @notice Returns the count of cleaned-up sarcophagi from the archaeologist @param archaeologist The address of the given archaeologist @return the number of cleaned-up sarcophagi from the archaeologist/
function archaeologistCleanupsCount(address archaeologist) public view virtual returns (uint256) { return _data.archaeologistCleanups[archaeologist].length; }
2,451,220
[ 1, 1356, 326, 1056, 434, 9426, 17, 416, 272, 11828, 23169, 346, 77, 628, 326, 6637, 8906, 3966, 376, 225, 6637, 8906, 3966, 376, 1021, 1758, 434, 326, 864, 6637, 8906, 3966, 376, 327, 326, 1300, 434, 9426, 17, 416, 272, 11828, 23169, 346, 77, 628, 326, 6637, 8906, 3966, 376, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6637, 8906, 3966, 376, 15007, 87, 1380, 12, 2867, 6637, 8906, 3966, 376, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 892, 18, 991, 8906, 3966, 376, 15007, 87, 63, 991, 8906, 3966, 376, 8009, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address to, uint256 value) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function _transferFrom( address from, address to, uint256 value ) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
* @dev to get the time for the laste liquidity trade trigger/
function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; }
7,286,811
[ 1, 869, 336, 326, 813, 364, 326, 1142, 73, 4501, 372, 24237, 18542, 3080, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17764, 48, 18988, 24237, 22583, 6518, 1435, 3903, 1338, 3061, 288, 203, 3639, 1142, 48, 18988, 24237, 22583, 6518, 273, 2037, 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 ]
./full_match/1/0x6a2Df7Fd15612079D1a72001F3a921Db792B2738/sources/lib/solady/src/utils/DateTimeLib.sol
@dev Returns the difference in minutes between `fromTimestamp` and `toTimestamp`.
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 result) { result = (toTimestamp - fromTimestamp) / 60; }
17,179,026
[ 1, 1356, 326, 7114, 316, 6824, 3086, 1375, 2080, 4921, 68, 471, 1375, 869, 4921, 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, 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, 3122, 13050, 12, 11890, 5034, 628, 4921, 16, 2254, 5034, 358, 4921, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 563, 13, 203, 565, 288, 203, 3639, 563, 273, 261, 869, 4921, 300, 628, 4921, 13, 342, 4752, 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: Unlicense pragma solidity ^0.6.2; import "./AccessPassSale.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract AccessPassSaleBridge is AccessControl { using SafeMath for uint256; AccessPassSale public accessPassSale; IERC20 public Stars; struct Tier { uint256 numPasses; uint256 passPrice; uint256 starsPerPass; bool paused; } constructor(address payable _accessPassSale, address _Stars) public { accessPassSale = AccessPassSale(_accessPassSale); Stars = IERC20(_Stars); } receive() external payable { uint256 tierPurchaseQuantity; uint256 ethLeft = msg.value; uint256 currCost; uint256 numPasses; uint256 passPrice; uint256 starsPerPass; uint256 starsPurchased; uint8 currTier; bool paused; for (uint8 i = 0; i < 5; i++) { currTier = 4 - i; (numPasses, passPrice, starsPerPass, paused) = accessPassSale.tiers( currTier ); if (!paused) { tierPurchaseQuantity = ethLeft.div(passPrice); if (numPasses < tierPurchaseQuantity) { tierPurchaseQuantity = numPasses; } currCost = passPrice.mul(tierPurchaseQuantity); ethLeft = ethLeft.sub(currCost); accessPassSale.purchase{value: currCost}(currTier); starsPurchased = starsPurchased.add( tierPurchaseQuantity.mul(starsPerPass) ); } } Stars.transfer(msg.sender, starsPurchased); if (ethLeft > 0) { msg.sender.transfer(ethLeft); } } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.6.2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import {Stars} from "./Stars.sol"; contract AccessPassSale is AccessControl { using SafeMath for uint256; bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); address payable public withdrawWallet; Stars stars; struct Tier { uint256 numPasses; uint256 passPrice; uint256 starsPerPass; bool paused; } mapping(uint8 => Tier) public tiers; event tierSet( uint8 tierNumber, uint256 numPasses, uint256 passPrice, uint256 starsPerPass ); event tierPaused(uint8 tierNumber, bool pauseStatus); event tierPurchased(uint8 tierNumber); modifier onlyAdmin { require(hasRole(ROLE_ADMIN, msg.sender), "Sender is not admin"); _; } /** * @dev Stores the addresses of the withdraw wallet and the first admin, * and stores the Stars contract. Allows users with the admin role to * grant/revoke the admin role from other users. * * Params: * _withdrawWallet: the address of the wallet that will receive the excess * stars when tiers are reduced or removed, and receive ether when ether is * withdrawn * starsAddress: the address of the Stars contract * _admin: the address of the first admin */ constructor( address payable _withdrawWallet, address starsAddress, address _admin ) public { withdrawWallet = _withdrawWallet; _setupRole(ROLE_ADMIN, _admin); _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); stars = Stars(starsAddress); } /** * @dev Sets the withdraw wallet * * Params: * _withdrawWallet: the address of the withdraw wallet * * Requirements: * Sender is admin */ function setWithdrawWallet(address payable _withdrawWallet) public onlyAdmin { withdrawWallet = _withdrawWallet; } /** * @dev Sets up the initial tiers to allow for the sale of 16 million Stars. * Transfers the required 16 million stars from the sender. * * Requirements: * Sender is admin * Sender has 16 million Stars * Contract is approved to transfer 16 million Stars from user * Tiers 1-5 contain no passes */ function initTiers() public onlyAdmin { for (uint8 i = 0; i <= 5; i++) { require(tiers[i].numPasses == 0, "Tiers 1-5 are not empty"); } stars.transferFrom(msg.sender, address(this), 180000000 ether); tiers[4] = Tier(25, 50 ether, 2000000 ether, false); tiers[3] = Tier(100, 25 ether, 500000 ether, false); tiers[2] = Tier(250, 10 ether, 100000 ether, false); tiers[1] = Tier(2000, 1 ether, 5000 ether, false); tiers[0] = Tier(45000000, 0.0003 ether, 1 ether, false); } /** * @dev Changes the specified tier. If the change allows for the sale of * more Stars than previously, the contract transfers the extra Stars * required from the sender. If the change allows for fewer Stars than * previously, the contract transfers its excess Stars to the sender. * * Params: * tierNumber: The number that identifies the tier to change * numPasses: The new number of passes to be sold in the tier * passPrice: The new price of a purchase from the tier * starsPerPass: The new number of stars that this tier grants upon purchase * * Requirements: * Sender is admin * If the change allows for the sale of more stars, the sender has the * required extra Stars, and the contract is approved to transfer those * Stars */ function setTier( uint8 tierNumber, uint256 numPasses, uint256 passPrice, uint256 starsPerPass ) public onlyAdmin { Tier storage selected = tiers[tierNumber]; uint256 newAmount = starsPerPass.mul(numPasses); uint256 currAmount = selected.starsPerPass.mul(selected.numPasses); if (newAmount > currAmount) { stars.transferFrom( msg.sender, address(this), newAmount.sub(currAmount) ); } else if (newAmount < currAmount) { stars.transfer(msg.sender, currAmount.sub(newAmount)); } tiers[tierNumber] = Tier(numPasses, passPrice, starsPerPass, false); emit tierSet(tierNumber, numPasses, passPrice, starsPerPass); } /** * @dev Sends users the appropriate number of Stars upon purchase, and * reduces the number of passes in the specified tier accordingly * * Params: * tierNumber: The number that identifies the tier to purchase from * * Requirements: * The transaction value is equal to the price of the specified tier * The tier contains more than 0 passes * The tier is not paused */ function purchase(uint8 tierNumber) public payable { Tier storage purchaseTier = tiers[tierNumber]; require( msg.value.mod(purchaseTier.passPrice) == 0, "Incorrect transaction value" ); uint256 passesToBuy = msg.value.div(purchaseTier.passPrice); require(purchaseTier.numPasses >= passesToBuy, "Not enough passes"); require( !purchaseTier.paused, "Purchases from this tier have been paused" ); stars.transfer(msg.sender, purchaseTier.starsPerPass.mul(passesToBuy)); purchaseTier.numPasses -= passesToBuy; emit tierPurchased(tierNumber); } /** * @dev Sets the pause status of the specified tiers * * Params: * tierNumbers: The list of numbers to identify the tiers to change * pauseStatus: The boolean value to set the pause status of specified tiers * * Requirements: * Sender is admin */ function setTiersPauseStatus(uint8[] memory tierNumbers, bool pauseStatus) public onlyAdmin { for (uint256 i = 0; i < tierNumbers.length; i++) { tiers[tierNumbers[i]].paused = pauseStatus; emit tierPaused(tierNumbers[i], pauseStatus); } } /** * @dev Sends all the ether in the contract to the withdraw wallet * * Requirements: * Sender is admin */ function withdrawETH() public onlyAdmin { withdrawWallet.transfer(address(this).balance); } /** * @dev Reduces the number of passes from specified tiers, and sends the * excess Stars the contract now has to the withdraw wallet * * Params: * tierNumbers: The list of numbers to identify the tiers to reduce * passAmounts: The number of passes to remove from each tier * * Requirements: * Sender is admin */ function reducePassesFromTiers( uint8[] memory tierNumbers, uint256[] memory passAmounts ) public onlyAdmin { uint256 withdrawAmount = 0; for (uint8 i = 0; i < tierNumbers.length; i++) { Tier storage selected = tiers[tierNumbers[i]]; require(passAmounts[i] <= selected.numPasses, "Not enough passes"); withdrawAmount += passAmounts[i].mul(selected.starsPerPass); selected.numPasses -= passAmounts[i]; } stars.transfer(withdrawWallet, withdrawAmount); } /** * @dev Removes all passes from specified tiers, and sends the excess Stars * the contract now has to the withdraw wallet * * Params: * tierNumbers: The list of numbers to identify the tiers to remove * * Requirements: * Sender is admin */ function removeTiers(uint8[] memory tierNumbers) public onlyAdmin { uint256 amount = 0; for (uint8 i = 0; i < tierNumbers.length; i++) { amount += tiers[tierNumbers[i]].numPasses.mul( tiers[tierNumbers[i]].starsPerPass ); tiers[tierNumbers[i]].numPasses = 0; } stars.transfer(withdrawWallet, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.6.2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./matic/BasicMetaTransaction.sol"; import "./openzeppelinModified/ERC20PresetMinterPauser.sol"; contract Stars is BasicMetaTransaction, ERC20PresetMinterPauser { using SafeMath for uint256; uint256 public nextMintStartTime; uint256 public totalSupplyThisYear; uint256 public remainingYearlyInflationAmt; uint256 public inflationBasisPoint; uint256 public mintLockPeriodSecs; /** * @dev Distributes tokens to inital holders, * locks the mint function for a specified time period, * sets the total supply at the beggining of the period, * sets inflation basis point numerator, * sets the mint lock period in secs. * * Parameters: * * - _admin: the Stars contract admin. * - _initialHolders: the initial holders of the Stars token. * - _prmintedAmounts: the token amount mantissas that _initialHolders will receive on deployment. * - _inflationBasisPoint: the yearly inflation rate basis point represented as a numerator. * - _mintLockPeriodSecs: the amount of seconds to lock minting after each mint. * * Requirements: * * - _initialHolders and _initialHolders must be same length. */ constructor( address _admin, address[] memory _initialHolders, uint256[] memory _premintedAmounts, uint256 _inflationBasisPoint, uint256 _mintLockPeriodSecs ) public ERC20PresetMinterPauser("Mogul Stars", "STARS", _admin) { require( _initialHolders.length == _premintedAmounts.length, "StarToken: Wrong lengths of arrays" ); for (uint256 i = 0; i < _initialHolders.length; i++) { _mint(_initialHolders[i], _premintedAmounts[i]); } nextMintStartTime = block.timestamp.add(_mintLockPeriodSecs); totalSupplyThisYear = totalSupply(); remainingYearlyInflationAmt = totalSupplyThisYear .mul(_inflationBasisPoint) .div(10000); inflationBasisPoint = _inflationBasisPoint; mintLockPeriodSecs = _mintLockPeriodSecs; } /** * @dev Admin function to mint up to x% of yearly supply at * the beggining of the period. * * Parameters: * * - recipient: the address of the Stars contract admin. * - amount: token amount mantissa to mint. * * Requirements: * * - caller must be admin. * - amount <= remainingYearlyInflationAmt. */ function mint(address recipient, uint256 amount) public override { require(admin == msgSender(), "Caller is not an admin"); require( amount <= remainingYearlyInflationAmt, "Minting too many tokens for this year" ); remainingYearlyInflationAmt = remainingYearlyInflationAmt.sub(amount); _mint(recipient, amount); } /** * @dev When mint lock period is over, admin will call this function * to reset the available minting amount to x% of total supply. * * Requirements: * * - caller must be admin. * - block.timestamp >= nextMintStartTime. */ function updateYearPeriod() public { require(admin == msgSender(), "Caller is not an admin"); require( block.timestamp >= nextMintStartTime, "Year period is not over" ); nextMintStartTime = nextMintStartTime.add(mintLockPeriodSecs); totalSupplyThisYear = totalSupply(); remainingYearlyInflationAmt = totalSupplyThisYear .mul(inflationBasisPoint) .div(10000); } /** * @dev Admin function to add a address to the whitelist. * When transfers are paused, whitlisted address will not be affected. * * Parameters: * * - whitelistAddress: the address to add to whitelist. * - isWhitelisted: whitelist status to change to. * * Requirements: * * - caller must be admin. */ function changeWhitelistStatus(address whitelistAddress, bool isWhitelisted) public { require(admin == msgSender(), "Caller is not an admin"); super._changeWhitelistStatus(whitelistAddress, isWhitelisted); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.6.2; import "@openzeppelin/contracts/math/SafeMath.sol"; contract BasicMetaTransaction { using SafeMath for uint256; event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) private nonces; function getChainID() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Main function to be called when user wants to execute meta transaction. * The actual function to be called should be passed as param with name functionSignature * Here the basic signature recovery is being used. Signature is expected to be generated using * personal_sign method. * @param userAddress Address of user trying to do meta transaction * @param functionSignature Signature of the actual function to be called via meta transaction * @param sigR R part of the signature * @param sigS S part of the signature * @param sigV V part of the signature */ function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { require( verify( userAddress, nonces[userAddress], getChainID(), functionSignature, sigR, sigS, sigV ), "Signer and signature do not match" ); nonces[userAddress] = nonces[userAddress].add(1); // Append userAddress at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); return returnData; } function getNonce(address user) external view returns (uint256 nonce) { nonce = nonces[user]; } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } function verify( address owner, uint256 nonce, uint256 chainID, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public view returns (bool) { bytes32 hash = prefixed( keccak256( abi.encodePacked(nonce, this, chainID, functionSignature) ) ); address signer = ecrecover(hash, sigV, sigR, sigS); require(signer != address(0), "Invalid signature"); return (owner == signer); } function msgSender() internal view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { return msg.sender; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; import "./ERC20.sol"; import "./ERC20Burnable.sol"; import "./ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, ERC20Burnable, ERC20Pausable { address public admin; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( string memory name, string memory symbol, address _admin ) public ERC20(name, symbol) { admin = _admin; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require( admin == _msgSender(), "ERC20PresetMinterPauser: must have minter role to mint" ); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( admin == _msgSender(), "ERC20PresetMinterPauser: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( admin == _msgSender(), "ERC20PresetMinterPauser: must have pauser role to unpause" ); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } function changeAdmin(address newAdmin) public { require(admin == _msgSender(), "Caller is not an admin"); admin = newAdmin; } function _changeWhitelistStatus( address whitelisteAddress, bool isWhitelisted ) internal virtual override { super._changeWhitelistStatus(whitelisteAddress, isWhitelisted); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable sender) { if(msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } } else { return msg.sender; } } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { mapping(address => bool) public whitelist; /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused or sender is whitelisted. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require( !paused() || whitelist[from] == true, "ERC20Pausable: token transfer while paused" ); } function _changeWhitelistStatus( address whitelisteAddress, bool isWhitelisted ) internal virtual { whitelist[whitelisteAddress] = isWhitelisted; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
* @dev Sets the withdraw wallet Params: _withdrawWallet: the address of the withdraw wallet Requirements: Sender is admin/
function setWithdrawWallet(address payable _withdrawWallet) public onlyAdmin { withdrawWallet = _withdrawWallet; }
11,653,381
[ 1, 2785, 326, 598, 9446, 9230, 8861, 30, 389, 1918, 9446, 16936, 30, 326, 1758, 434, 326, 598, 9446, 9230, 29076, 30, 15044, 353, 3981, 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, 444, 1190, 9446, 16936, 12, 2867, 8843, 429, 389, 1918, 9446, 16936, 13, 203, 3639, 1071, 203, 3639, 1338, 4446, 203, 565, 288, 203, 3639, 598, 9446, 16936, 273, 389, 1918, 9446, 16936, 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 ]
./partial_match/1/0x6DfACd64037f284Cd4d397f725888291bD96FAF8/sources/contracts/cedar/terms/lib/TermsLogic.sol
@notice activates / deactivates the terms of use.
function setTermsActivation(TermsDataTypes.Terms storage termsData, bool _active) external { if (_active) { _activateTerms(termsData); _deactivateTerms(termsData); } }
4,004,654
[ 1, 11422, 815, 342, 443, 11422, 815, 326, 6548, 434, 999, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 11673, 14857, 12, 11673, 751, 2016, 18, 11673, 2502, 6548, 751, 16, 1426, 389, 3535, 13, 3903, 288, 203, 3639, 309, 261, 67, 3535, 13, 288, 203, 5411, 389, 10014, 11673, 12, 10112, 751, 1769, 203, 5411, 389, 323, 10014, 11673, 12, 10112, 751, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: AngoraStaker.sol // File: anotest.sol pragma solidity ^0.8.13; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Interface of the 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 Returns the amount of decimals in the token */ function decimals() 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 ); } /** * @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 Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } /** * @dev Returns the floor of the division of two numbers * * This divides two numbers and rounds down */ function floorDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; return a / b - (a % b == 0 ? 1 : 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); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // solhint-disable not-rely-on-time, avoid-low-level-calls contract AngoraStaker is Ownable { using SafeERC20 for IERC20; IERC20 public stakingToken; // Staking token uint256 private _totalSupply; // Total staked amount uint256 private _totalRewards; // Total amount for rewards uint256 private _stakeRequired = 100e18; // Minimum stake amount // Set standard contract data in ContractData struct ContractData private _data = ContractData({ isActive: 0, reentrant: 1, timeFinished: 0, baseMultiplier: 1e18 }); mapping (address => UserDeposit) private _deposits; // Track all user deposits mapping (address => uint256) private _userRewardPaid; // Track all user claims // Store global contract data in packed struct struct ContractData { uint8 isActive; uint8 reentrant; uint64 timeFinished; uint64 baseMultiplier; } // Store user deposit data in packed struct struct UserDeposit { uint8 lock; // 1 = 1 7 days; 2 = 30 days; 3 = 90 days uint64 timestamp; uint256 staked; } constructor(IERC20 ) { stakingToken = IERC20(0x60a5C1c2f75f61B1B8aDFD66B04dcE40d29fEecE); } // ===== MODIFIERS ===== // /** * @dev Reentrancy protection */ modifier nonReentrant() { require(_data.reentrant == 1, "Reentrancy not allowed"); _data.reentrant = 2; _; _data.reentrant = 1; } // ===== PAYABLE DEFAULTS ====== // // ===== VIEW FUNCTIONS ===== // /** * @dev Check total amount staked * * @return totalSupply the total amount staked */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Check total rewards amount * * @notice this assumes that staking token is the same as reward token * * @return totalRewards the total balance of contract - amount staked */ function totalRewards() external view returns (uint256) { return _totalRewards; } /** * @dev Check base multiplier of contract * * @notice Normalized to 1e18 = 100%. Contract currently uses a 1x, 2x, and 3x multiplier * based on how long the user locks their stake for (in UserDeposit struct). * Therefore max baseMultiplier would be <= 333e15 (33.3%). * * @return baseMultiplier 1e18 normalized percentage to start */ function baseMultiplier() external view returns (uint256) { return _data.baseMultiplier; } /** * @dev Checks amount staked for account. * * @param account the user account to look up. * * @return staked the total amount staked from account. */ function balanceOf(address account) external view returns (uint256) { return _deposits[account].staked; } /** * @dev Checks all user deposit data for account. * * @param account the user account to look up. * * @return userDeposit the entire deposit data. */ function getDeposit(address account) external view returns (UserDeposit memory) { return _deposits[account]; } /** * @dev Checks if staking contract is active. * * @notice _isActive is stored as uint where 0 = false; 1 = true. * * @return isActive boolean true if 1; false if not. */ function isActive() external view returns (bool) { return _data.isActive == 1; } /** * @dev Check current minimum stake amount * * @return minimum the min stake amount */ function getMinimumStake() external view returns (uint256) { return _stakeRequired; } /** * @dev Checks when staking finished. * * @notice if 0, staking is still active. * * @return timeFinished the block timestamp of when staking completed. */ function timeEnded() external view returns (uint256) { return _data.timeFinished; } /** * @dev Checks pending rewards currently accumulating for month. * * @notice These rewards are prorated for the current period (month). * Users cannot withdraw rewards until a full month has passed. * If a user makes an additional deposit mid-month, these pending rewards * will be added to their new staked amount, and lock time reset. * * @param account the user account to use for calculation. * * @return pending the pending reward for the current period. */ function pendingReward(address account) public view returns (uint256) { // If staking rewards are finished, should always return 0 if (_data.timeFinished > 0) { return 0; } // Get deposit record for account UserDeposit memory userDeposit = _deposits[account]; if (userDeposit.staked == 0) { return 0; } // Calculate total time, week/months, and time delta between uint256 timePassed = block.timestamp - userDeposit.timestamp; uint256 daysPassed = timePassed > 0 ? Math.floorDiv(timePassed, 86400) : 0; uint256 interimTime = timePassed - (daysPassed * 86400); // Calculate pending rewards based on prorated time from the current period uint256 pending = userDeposit.staked * (_data.baseMultiplier * uint256(userDeposit.lock)) / 1e18 * interimTime / 2628000; return pending; } /** * @dev Checks current earned rewards for account. * * @notice These rewards are calculated by the number of full week/months * passed since deposit, based on the multiplier set by the user based on * lockup time (i.e. 1x for 7 days, 2x for 30 days, 3x for 90 days). * This function subtracts withdrawn rewards from the calculation so if * total rewards are 100 coins, but 50 are withdrawn, * it should return 50. * * @param account the user account to use for calculation. * * @return totalReward the total rewards the user has earned. */ function earned(address account) public view returns (uint256) { // Get deposit record for account UserDeposit memory userDeposit = _deposits[account]; // Get total rewards paid already uint256 rewardPaid = _userRewardPaid[account]; // If a final timestamp is set, use that instead of current timestamp uint256 endTime = _data.timeFinished == 0 ? block.timestamp : _data.timeFinished; uint256 daysPassed = Math.floorDiv(endTime - userDeposit.timestamp, 86400); // If no days have passed, return 0 if (daysPassed == 0) return 0; // Calculate total earned - amount already paid uint256 totalReward = userDeposit.staked * ((_data.baseMultiplier * userDeposit.lock) * daysPassed) / 1e18 - rewardPaid; return totalReward; } /** * @dev Check if user can withdraw their stake. * * @notice uses the user's lock chosen on deposit, multiplied * by the amount of seconds in a day. * * @param account the user account to check. * * @return canWithdraw boolean value determining if user can withdraw stake. */ function withdrawable(address account) public view returns (bool) { UserDeposit memory userDeposit = _deposits[account]; uint256 unlockTime = _getUnlockTime(userDeposit.timestamp, userDeposit.lock); if (block.timestamp < unlockTime) { return false; } else { return true; } } /** * @dev Check if current time past lock time. * * @param timestamp the user's initial lock time. * @param lock the lock multiplier chosen (1 = 7 days, 2 = 30 days, 3 = 90 days). * * @return unlockTime the timestamp after which a user can withdraw. */ function _getUnlockTime(uint64 timestamp, uint8 lock) private pure returns (uint256) { if (lock == 1) { // Add one week return timestamp + (86400 * 7); } else if (lock == 2) { // Add one months return timestamp + (86400 * 30); } else { // Add three months return timestamp + (86400 * 90); } } // ===== MUTATIVE FUNCTIONS ===== // /** * @dev Deposit and stake funds * * @param amount the amount of tokens to stake * @param lock the lock multiplier (1 = 7 days, 2 = 30 days, 3 = 90 days). * * @notice Users cannot change lock periods if adding additional stake */ function deposit(uint256 amount, uint8 lock) external payable nonReentrant { // Check if staking is active require(_data.isActive != 0, "Staking inactive"); require(lock > 0 && lock < 4, "Lock must be 1, 2, or 3"); require(amount > 0, "Amount cannot be 0"); // Get existing user deposit. All 0s if non-existent UserDeposit storage userDeposit = _deposits[msg.sender]; require(userDeposit.staked + amount >= _stakeRequired, "Need to meet minimum stake"); // Transfer token stakingToken.transferFrom(msg.sender, address(this), amount); // If user's current stake is greater than 0, we need to get // earned and pending rewards and add them to stake and total if (userDeposit.staked > 0) { uint256 earnedAmount = earned(msg.sender); uint256 pendingAmount = pendingReward(msg.sender); uint256 combinedAmount = earnedAmount + pendingAmount; // Update user's claimed amount _userRewardPaid[msg.sender] += combinedAmount; // Update total rewards by subtracting earned/pending amounts _totalRewards -= combinedAmount; // Update total supply and current stake _totalSupply += amount + combinedAmount; // Save new deposit data userDeposit.staked += amount + combinedAmount; userDeposit.timestamp = uint64(block.timestamp); if (lock > userDeposit.lock || block.timestamp > _getUnlockTime(userDeposit.timestamp, userDeposit.lock)) { userDeposit.lock = lock; } } else { // Create new deposit record for user with new lock time userDeposit.lock = lock; userDeposit.timestamp = uint64(block.timestamp); userDeposit.staked = amount; // Add new amount to total supply _totalSupply += amount; } emit Deposited(msg.sender, amount); } /** * @dev Withdraws a user's stake. * * @param amount the amount to withdraw. * * @notice must be past unlock time. */ function withdraw(uint256 amount) external payable nonReentrant { // Get user deposit info in storage UserDeposit storage userDeposit = _deposits[msg.sender]; // Check if user can withdraw amount require(userDeposit.staked > 0, "User has no stake"); require(withdrawable(msg.sender), "Lock still active"); require(amount <= userDeposit.staked, "Withdraw amount too high"); // Get earned rewards and paid rewards uint256 earnedRewards = earned(msg.sender); // Calculate amount to withdraw uint256 amountToWithdraw = amount + earnedRewards; // Check if user is withdrawing their total stake if (userDeposit.staked == amount) { // If withdrawing full amount we no longer care about paid rewards _userRewardPaid[msg.sender] = 0; // We only need to set staked to 0 because it is the only // value checked on future deposits userDeposit.staked = 0; } else { uint256 daysForStaking; if (userDeposit.lock == 1) { daysForStaking = 7; } else if (userDeposit.lock == 2) { daysForStaking = 30; } else if (userDeposit.lock == 3) { daysForStaking = 90; } // Remove amount from staked userDeposit.staked -= amount; // Start fresh _userRewardPaid[msg.sender] = 0; // Set new timestamp to 7, 30, or 90 days prior so users can still withdraw // from original stake time but rewards essentially restart userDeposit.timestamp = uint64(block.timestamp - (86400 * daysForStaking)); _userRewardPaid[msg.sender] = earned(msg.sender); } // Update total staked amount and rewards amount _totalSupply -= amount; _totalRewards -= earnedRewards; // Transfer tokens to user stakingToken.safeTransfer(msg.sender, amountToWithdraw); emit Withdrawal(msg.sender, amount); } /** * @dev Emergency withdrawal in case rewards have been pulled * * @notice Only available after staking is closed and * all reward tokens have been withdrawn. */ function emergencyWithdrawal() external payable { require(_data.isActive == 0, "Staking must be closed"); require(_data.timeFinished > 0, "Staking must be closed"); require(_totalRewards == 0, "Use normal withdraw"); // Get user deposit info uint256 amountToWithdraw = _deposits[msg.sender].staked; require(amountToWithdraw > 0, "No stake to withdraw"); // Reset all data _userRewardPaid[msg.sender] = 0; _deposits[msg.sender].staked = 0; // Update total staked amount _totalSupply -= amountToWithdraw; // Transfer tokens to user stakingToken.safeTransfer(msg.sender, amountToWithdraw); emit Withdrawal(msg.sender, amountToWithdraw); } /** * @dev Claims earned rewards. */ function claimRewards() external payable nonReentrant { // Get user's earned rewards uint256 amountToWithdraw = earned(msg.sender); require(amountToWithdraw > 0, "No rewards to withdraw"); require(amountToWithdraw <= _totalRewards, "Not enough rewards in contract"); // Add amount to user's withdraw rewards _userRewardPaid[msg.sender] += amountToWithdraw; // Update total rewards _totalRewards -= amountToWithdraw; stakingToken.safeTransfer(msg.sender, amountToWithdraw); emit RewardsClaimed(amountToWithdraw); } /** * @dev Update minimum stake amount * * @param minimum the new minimum stake account */ function updateMinimum(uint256 minimum) external payable onlyOwner { _stakeRequired = minimum; emit MinimumUpdated(minimum); } function updateMultiplier(uint64 multiplier) external payable onlyOwner { _data.baseMultiplier = multiplier; emit MultiplierUpdated(multiplier); } /** * @dev Funds rewards for contract * * @param amount the amount of tokens to fund */ function fundStaking(uint256 amount) external payable onlyOwner { require(amount > 0, "Amount cannot be 0"); _totalRewards += amount; stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit StakingFunded(amount); } /** * @dev Withdraws rewards tokens * * @notice Requires rewards to be closed. This * function is intended to pull leftover tokens * once all users have claimed rewards. */ function withdrawRewardTokens() external payable onlyOwner { require(_data.timeFinished > 0, "Staking must be complete"); uint256 amountToWithdraw = _totalRewards; _totalRewards = 0; stakingToken.safeTransfer(owner(), amountToWithdraw); } /** * @dev Closes reward period * * @notice This is a one-way function. Once staking is closed, it * cannot be re-enabled. Use cautiously. */ function closeRewards() external payable onlyOwner { require(_data.isActive == 1, "Contract already inactive"); _data.isActive = 0; _data.timeFinished = uint64(block.timestamp); emit StakingEnded(block.timestamp); } /** * @dev Enables staking */ function enableStaking() external payable onlyOwner { require(_data.isActive == 0, "Staking already active"); _data.isActive = 1; emit StakingEnabled(); } // ===== EVENTS ===== // event StakingFunded(uint256 amount); event StakingEnabled(); event StakingEnded(uint256 timestamp); event RewardsClaimed(uint256 amount); event Deposited(address indexed account, uint256 amount); event Withdrawal(address indexed account, uint256 amount); event MinimumUpdated(uint256 newMinimum); event MultiplierUpdated(uint256 newMultiplier); }
* @dev Check current minimum stake amount @return minimum the min stake amount/
function getMinimumStake() external view returns (uint256) { return _stakeRequired; }
5,725,414
[ 1, 1564, 783, 5224, 384, 911, 3844, 327, 5224, 326, 1131, 384, 911, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30665, 510, 911, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 334, 911, 3705, 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 ]
pragma solidity ^0.4.22; import "../IDaoObserver.sol"; import "../governance/IProposal.sol"; library UtilsLib { function bytes32ToString(bytes32 x) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function sqrt(uint x) public pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function stringToBytes32(string memory source) public view returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function isAddressInArray(address[] storage _addressArray, address _targetAddress) public view returns(bool) { // address[] memory parts = _addressArray; address item = _targetAddress; bool isInArray = false; for(uint j=0; j<_addressArray.length; ++j) { if(_addressArray[j]==item) { isInArray = true; } } return isInArray; } function isBytes32InArray(bytes32[] storage _bytes32Array, bytes32 _targetBytes32) public view returns(bool) { // bytes32[] memory _bytes32Array = _bytes32Array; bytes32 item = _targetBytes32; bool isInArray = false; for(uint j=0; j<_bytes32Array.length; ++j) { if(_bytes32Array[j]==item) { isInArray = true; } } return isInArray; } function removeBytes32FromArray(bytes32[] storage _bytes32Array, bytes32 _targetBytes32) public { // bytes32[] memory _bytes32Array = _bytes32Array; bytes32 item = _targetBytes32; uint index = _bytes32Array.length; for(uint j=0; j<_bytes32Array.length; ++j) { if(_bytes32Array[j]==item) { index = j; } } require(index<_bytes32Array.length); // if member is not found -> exception if(index!=(_bytes32Array.length - 1)) { _bytes32Array[index] = _bytes32Array[_bytes32Array.length-1]; } delete _bytes32Array[_bytes32Array.length-1]; // delete last element _bytes32Array.length--; // return _bytes32Array; } function removeAddressFromArray(address[] storage _addressArray, address _targetAddress) public { // address[] memory parts = _addressArray; address item = _targetAddress; uint index = _addressArray.length; for(uint j=0; j<_addressArray.length; ++j) { if(_addressArray[j]==item) { index = j; } } require(index<_addressArray.length); // if member is not found -> exception if(index!=(_addressArray.length - 1)) { _addressArray[index] = _addressArray[_addressArray.length-1]; } delete _addressArray[_addressArray.length-1]; // delete last element _addressArray.length--; // return _addressArray; } function removeProposalFromArray(IProposal[] storage _proposalsArray, IProposal _targetProposal) public { // IProposal[] memory _proposalsArray = _proposalsArray; IProposal item = _targetProposal; uint index = _proposalsArray.length; for(uint j=0; j<_proposalsArray.length; ++j) { if(_proposalsArray[j]==item) { index = j; } } require(index<_proposalsArray.length); // if member is not found -> exception if(index!=(_proposalsArray.length - 1)) { _proposalsArray[index] = _proposalsArray[_proposalsArray.length-1]; } delete _proposalsArray[_proposalsArray.length-1]; // delete last element _proposalsArray.length--; // return _proposalsArray; } function removeDaoObserverFromArray(IDaoObserver[] storage _daoObserversArray, IDaoObserver _targetDaoObserver) public { // IDaoObserver[] memory _daoObserversArray = _daoObserversArray; IDaoObserver item = _targetDaoObserver; uint index = _daoObserversArray.length; for(uint j=0; j<_daoObserversArray.length; ++j) { if(_daoObserversArray[j]==item) { index = j; } } require(index<_daoObserversArray.length); // if member is not found -> exception if(index!=(_daoObserversArray.length - 1)) { _daoObserversArray[index] = _daoObserversArray[_daoObserversArray.length-1]; } delete _daoObserversArray[_daoObserversArray.length-1]; // delete last element _daoObserversArray.length--; } }
address[] memory parts = _addressArray;
function isAddressInArray(address[] storage _addressArray, address _targetAddress) public view returns(bool) { address item = _targetAddress; bool isInArray = false; for(uint j=0; j<_addressArray.length; ++j) { if(_addressArray[j]==item) { isInArray = true; } } return isInArray; }
12,692,087
[ 1, 2867, 8526, 3778, 2140, 273, 389, 2867, 1076, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 202, 915, 353, 1887, 382, 1076, 12, 2867, 8526, 2502, 389, 2867, 1076, 16, 1758, 389, 3299, 1887, 13, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 202, 202, 2867, 761, 273, 389, 3299, 1887, 31, 203, 202, 202, 6430, 8048, 1076, 273, 629, 31, 203, 202, 202, 1884, 12, 11890, 525, 33, 20, 31, 525, 32, 67, 2867, 1076, 18, 2469, 31, 965, 78, 13, 288, 203, 1082, 202, 430, 24899, 2867, 1076, 63, 78, 65, 631, 1726, 13, 288, 203, 9506, 202, 291, 382, 1076, 273, 638, 31, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 202, 2463, 8048, 1076, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/421613/0xbc695B02d93052029D31A991EFc07Ad4C6FcFc1b/sources/project_/contracts/DogiumRefinery.sol
Initial number of ETH deposited in the LP
uint256 public initialLPEth;
11,576,618
[ 1, 4435, 1300, 434, 512, 2455, 443, 1724, 329, 316, 326, 511, 52, 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, 2254, 5034, 1071, 2172, 48, 1423, 451, 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 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Metadata.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721MetadataMintable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Metadata.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/drafts/Counters.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /// @title A Nifties exchange game to incentivize tourism and onboard to crypto /// @author santteegt /// @notice NFTs Market price is artificially calculated based on randomness feed from previous block hashes and user demand /// @dev Contract can be upgraded through a proxy contract supplied by OpenZeppelin SDK contract StampCollectible is Initializable, Pausable, ERC721MetadataMintable { /// Library used to perform unit increment/decrements using Counters for Counters.Counter; /// Library to avoid overflow/underflow bugs using SafeMath for uint256; /// Data structure that represents a NFT Tourist stamp struct Stamp { uint256 price; uint256 maxClones; uint256 inWild; uint256 clonedFrom; } struct ClonedStamp { bool owned; uint tokenId; } /// Tracks the total minted stamps Counters.Counter public totalMinted; /// Store all minted stamps // Stamp[] public stamps; mapping (uint256 => Stamp) public stamps; /// mapping (uint256 => bool) public ownedTokensIndex; /// Game parameter to provide an scarce amount of stamps uint256 public maxClones; /// Game parameter thah establish the depth of blockhashes to scan during NFT price estimate // uint8 constant private PRICEDEPTH = 255; uint8 private priceDepth; /// Cost multiplier to transform NFT price (in finney) to ETH // uint256 constant private COSTMULTIPLIER = 1000000000000; uint256 private costMultiplier; /// Maintains a record of minted NFTS and ownership per account // mapping (address => mapping (uint256 => bool)) public balances; mapping (address => mapping (uint256 => ClonedStamp)) public balances; /// Verify that the priceDepth parameters is within the max No. of historical blocks a contract can track modifier checkMaxBlockDepth(uint _value) { require(_value > 0 && _value <= 255, "Price Depth parameter must be within then range [1-255]"); _; } /// Triggered when a new Gen0 stamp is minted by the contract owner event MintedStamp(address indexed owner, uint256 tokenId, uint256 price); /// Triggered when a stamp is cloned and minted to a user event NewStamp(address indexed owner, uint256 tokenId, uint256 price); /// Triggered when a cloned stamp is returned to the contract and thus burned event BurnedStamp(address indexed owner, uint256 tokenId, uint256 clonedTokenId); /// @dev This constructor was deprecated in favour of the initialize function /// @dev so the contract can be upgraded through a proxy contract // constructor(uint256 _maxClones) ERC721Metadata("CryptoStamps", "STAMPS") public { // maxClones = _maxClones; // if(stamps.length == 0) { // Stamp memory _dummy = Stamp({ // price: 0, maxClones: 0, inWild: 0, clonedFrom: 0}); // stamps.push(_dummy); // } // } /** @dev Initialize current and derived contracts * @param _maxClones Maximum number of clones allowed per Gen0 NFT * @param _priceDepth Game parameter thah establish the depth of blockhashes to scan during NFT price estimate * @param _costMultiplier Cost multiplier to transform NFT price (in finney) to ETH * @param _name NFT name * @param _symbol NFT symbol */ function initialize(uint256 _maxClones, uint8 _priceDepth, uint256 _costMultiplier, string memory _name, string memory _symbol) public initializer // ensures that the contract only initilizes once checkMaxBlockDepth(_maxClones) { Pausable.initialize(msg.sender); if(!ERC721._hasBeenInitialized()) { ERC721.initialize(); } if(!ERC721Metadata._hasBeenInitialized()) { ERC721Metadata.initialize(_name, _symbol); } ERC721MetadataMintable.initialize(msg.sender); maxClones = _maxClones; priceDepth = _priceDepth; costMultiplier = _costMultiplier; Stamp memory _dummy = Stamp({ price: 0, maxClones: 0, inWild: 0, clonedFrom: 0}); stamps[0] = _dummy; } /** @dev Calculate the new NFT price based on demand and randomness based on past block hashes * @notice Market value is artificially generated for the game using the entropy found in past block hashes * @param _index NFT index in storage * @return uint16 NFt new estimate market price */ function getNFTPrice(uint256 _index) internal view returns (uint16) { Stamp memory stamp = stamps[_index]; uint256 x = 0; for(uint8 depth = priceDepth; depth > 0 ; depth--) { bytes32 blockHash = blockhash(block.number-depth); x += convert(blockHash[_index * 2]) << 8 | convert(blockHash[_index * 2 + 1]); } return uint16(x / priceDepth) + uint16(stamp.inWild); } /** @dev Helper function to convert a bytes32 to uint * @param _b bytes32 data hash * @return uint uint representation of _b */ function convert(bytes32 _b) internal pure returns (uint) { return uint(_b); } /** @dev Mint a Gen0 stamp * @notice This function can only be called by the contract owner * @param _priceFinney Initial NFT price in finney * @param _tokenURI URI of the associated digital collectible art * @return bool true if Gen0 NFT is minted */ function mint(uint256 _priceFinney, string memory _tokenURI) public onlyMinter whenNotPaused returns (bool) { Stamp memory collectible = Stamp({ price: _priceFinney.mul(costMultiplier), maxClones: maxClones, inWild: 0, clonedFrom: 0 }); totalMinted.increment(); uint256 tokenId = totalMinted.current(); stamps[tokenId] = collectible; ownedTokensIndex[tokenId] = true; emit MintedStamp(msg.sender, tokenId, _priceFinney); return mintWithTokenURI(msg.sender, tokenId, _tokenURI); } /** @dev Allow to buy a cloned stamp from minted Gen0 NFTs * @param _tokenId Gen0 NFT index in storage * @return uint tokenId corresponding to the cloned NFT */ function buyStamp(address sender, uint256 _tokenId) public payable whenNotPaused returns (uint) { Stamp storage stamp = stamps[_tokenId]; require(stamp.clonedFrom == 0, "You can only generate new stamps from Gen0 NFTs"); require(!balances[sender][_tokenId].owned, "You already own this stamp"); require(stamp.inWild.add(1) <= stamp.maxClones, "Max clones have been reached"); require(msg.value >= stamp.price, "Not enough funds"); stamp.inWild = stamp.inWild.add(1); stamp.price = uint256(getNFTPrice(_tokenId)).mul(costMultiplier); /// mint and increase total minted totalMinted.increment(); uint tokenId = totalMinted.current(); Stamp memory clonedStamp = Stamp({ price: stamp.price, maxClones: 0, inWild: 0, clonedFrom: _tokenId }); stamps[tokenId] = clonedStamp; ownedTokensIndex[tokenId] = true; _mint(sender, tokenId); balances[sender][_tokenId].owned = true; balances[sender][_tokenId].tokenId = tokenId; // emit NewStamp(msg.sender, _tokenId, stamp.price); emit NewStamp(sender, tokenId, msg.value); return tokenId; } /** @dev Allow to sell an owned stamp and profit/loose based on current market price * @param _tokenId Gen0 NFT index in storage * @return bool true if processed */ function sellStamp(uint256 _tokenId) public whenNotPaused returns (bool) { require(balances[msg.sender][_tokenId].owned, "User does not own this stamp"); Stamp storage stamp = stamps[_tokenId]; uint256 payout = stamp.price; require(address(this).balance >= payout, "Prize pot is almost empty so it is no longer possible to sell stamps"); stamp.inWild = stamp.inWild.sub(1); stamp.price = uint256(getNFTPrice(_tokenId)).mul(costMultiplier); ClonedStamp storage clonedStamp = balances[msg.sender][_tokenId]; clonedStamp.owned = false; // burn token _burn(clonedStamp.tokenId); ownedTokensIndex[clonedStamp.tokenId] = false; emit BurnedStamp(msg.sender, _tokenId, clonedStamp.tokenId); delete stamps[clonedStamp.tokenId]; // TODO: disabled when upgrading the contract // msg.sender.transfer(payout); // This approach can block the asset if owned by a bad actor (contract account) // TODO: to be addded in an upgraded version of the contract outstandingBalance[msg.sender] = outstandingBalance[msg.sender].add(payout); return true; } /** @dev Fallback function to allow the contract accept deposits in ETH * @notice deposits can be crodwsourced to fund the Prize pot */ function () external payable whenNotPaused { } /// Maintains a record of outstanding balance owned to users before withdrawal /// Required to implement the Pull vs Push design pattern for payments /// TODO: to be included later in an upgradable contract mapping (address => uint) public outstandingBalance; /// Triggered when a user withdraw her outstanding balance from selling stamps in the market /// TODO: this has to be added as an upgrade event WithdrawnBalance(address indexed owner, uint256 amount); /** @dev Allow users to withdraw funds from sold stamps. Required to enable a pull vs push design pattern * @return bool true if processed */ /// TODO: to be addded in an upgraded version of the contract function withdraw() public whenNotPaused returns (bool) { require(outstandingBalance[msg.sender] > 0, "You dont have any outstanding balance to withdraw"); uint amount = outstandingBalance[msg.sender]; outstandingBalance[msg.sender] = 0; emit WithdrawnBalance(msg.sender, amount); msg.sender.transfer(amount); return true; } }
* @dev Allow to buy a cloned stamp from minted Gen0 NFTs @param _tokenId Gen0 NFT index in storage @return uint tokenId corresponding to the cloned NFT/ mint and increase total minted
function buyStamp(address sender, uint256 _tokenId) public payable whenNotPaused returns (uint) { Stamp storage stamp = stamps[_tokenId]; require(stamp.clonedFrom == 0, "You can only generate new stamps from Gen0 NFTs"); require(!balances[sender][_tokenId].owned, "You already own this stamp"); require(stamp.inWild.add(1) <= stamp.maxClones, "Max clones have been reached"); require(msg.value >= stamp.price, "Not enough funds"); stamp.inWild = stamp.inWild.add(1); stamp.price = uint256(getNFTPrice(_tokenId)).mul(costMultiplier); totalMinted.increment(); uint tokenId = totalMinted.current(); Stamp memory clonedStamp = Stamp({ price: stamp.price, maxClones: 0, inWild: 0, clonedFrom: _tokenId }); stamps[tokenId] = clonedStamp; ownedTokensIndex[tokenId] = true; _mint(sender, tokenId); balances[sender][_tokenId].owned = true; balances[sender][_tokenId].tokenId = tokenId; return tokenId; }
15,870,834
[ 1, 7009, 358, 30143, 279, 13027, 14429, 628, 312, 474, 329, 10938, 20, 423, 4464, 87, 225, 389, 2316, 548, 10938, 20, 423, 4464, 770, 316, 2502, 327, 2254, 1147, 548, 4656, 358, 326, 13027, 423, 4464, 19, 312, 474, 471, 10929, 2078, 312, 474, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 30143, 8860, 12, 2867, 5793, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 8843, 429, 203, 3639, 1347, 1248, 28590, 203, 3639, 1135, 261, 11890, 13, 288, 203, 5411, 934, 931, 2502, 14429, 273, 14429, 87, 63, 67, 2316, 548, 15533, 203, 5411, 2583, 12, 14317, 18, 830, 8184, 1265, 422, 374, 16, 315, 6225, 848, 1338, 2103, 394, 14429, 87, 628, 10938, 20, 423, 4464, 87, 8863, 203, 5411, 2583, 12, 5, 70, 26488, 63, 15330, 6362, 67, 2316, 548, 8009, 995, 329, 16, 315, 6225, 1818, 4953, 333, 14429, 8863, 203, 5411, 2583, 12, 14317, 18, 267, 59, 545, 18, 1289, 12, 21, 13, 1648, 14429, 18, 1896, 2009, 5322, 16, 315, 2747, 927, 5322, 1240, 2118, 8675, 8863, 203, 5411, 2583, 12, 3576, 18, 1132, 1545, 14429, 18, 8694, 16, 315, 1248, 7304, 284, 19156, 8863, 203, 5411, 14429, 18, 267, 59, 545, 273, 14429, 18, 267, 59, 545, 18, 1289, 12, 21, 1769, 203, 5411, 14429, 18, 8694, 273, 2254, 5034, 12, 588, 50, 4464, 5147, 24899, 2316, 548, 13, 2934, 16411, 12, 12398, 23365, 1769, 203, 203, 5411, 2078, 49, 474, 329, 18, 15016, 5621, 203, 5411, 2254, 1147, 548, 273, 2078, 49, 474, 329, 18, 2972, 5621, 203, 5411, 934, 931, 3778, 13027, 8860, 273, 934, 931, 12590, 203, 7734, 6205, 30, 14429, 18, 8694, 16, 203, 7734, 943, 2009, 5322, 30, 374, 16, 203, 7734, 316, 59, 545, 30, 374, 16, 203, 7734, 13027, 1265, 30, 389, 2316, 548, 203, 5411, 15549, 203, 5411, 14429, 2 ]
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
* @notice Provides the percentage of the liquidity pool to be burned. This amount should account approximately for the swap fees collected by the liquidity pool during a 7-day period. @return _burningRate A percent value that corresponds to the current amount of the liquidity pool to be burned at each 7-day cycle./
function liquidityPoolBurningRate() public view override returns (uint256 _burningRate) { return lpm.burningRate; }
2,650,906
[ 1, 17727, 326, 11622, 434, 326, 4501, 372, 24237, 2845, 358, 506, 18305, 329, 18, 540, 1220, 3844, 1410, 2236, 26962, 5173, 364, 326, 7720, 1656, 281, 540, 12230, 635, 326, 4501, 372, 24237, 2845, 4982, 279, 2371, 17, 2881, 3879, 18, 327, 389, 70, 321, 310, 4727, 432, 5551, 460, 716, 13955, 358, 326, 783, 8227, 3844, 434, 326, 4501, 372, 24237, 2845, 358, 506, 18305, 329, 622, 8227, 1517, 2371, 17, 2881, 8589, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 915, 4501, 372, 24237, 2864, 38, 321, 310, 4727, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 389, 70, 321, 310, 4727, 13, 203, 202, 95, 203, 202, 202, 2463, 328, 7755, 18, 70, 321, 310, 4727, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// https://docs.erisindustries.com/tutorials/solidity/solidity-1/ // Base class for contracts that are used in a doug system. contract DougEnabled { address DOUG; function setDougAddress(address dougAddr) returns (bool result){ // Once the doug address is set, don't allow it to be set again, except by the // doug contract itself. if(DOUG != 0x0 && msg.sender != DOUG){ return false; } DOUG = dougAddr; return true; } // Makes it so that Doug is the only contract that may kill it. function remove(){ if(msg.sender == DOUG){ suicide(DOUG); } } } // The Doug contract. contract Doug { address owner; // This is where we keep all the contracts. mapping (bytes32 => address) public contracts; modifier onlyOwner { //a modifier to reduce code replication if (msg.sender == owner) // this ensures that only the owner can access the function _ } // Constructor function Doug(){ owner = msg.sender; } // Add a new contract to Doug. This will overwrite an existing contract. function addContract(bytes32 name, address addr) onlyOwner returns (bool result) { DougEnabled de = DougEnabled(addr); // Don't add the contract if this does not work. if(!de.setDougAddress(address(this))) { return false; } contracts[name] = addr; return true; } // Remove a contract from Doug. We could also suicide if we want to. function removeContract(bytes32 name) onlyOwner returns (bool result) { if (contracts[name] == 0x0){ return false; } contracts[name] = 0x0; return true; } function remove() onlyOwner { address fm = contracts["fundmanager"]; address perms = contracts["perms"]; address permsdb = contracts["permsdb"]; address bank = contracts["bank"]; address bankdb = contracts["bankdb"]; // Remove everything. if(fm != 0x0){ DougEnabled(fm).remove(); } if(perms != 0x0){ DougEnabled(perms).remove(); } if(permsdb != 0x0){ DougEnabled(permsdb).remove(); } if(bank != 0x0){ DougEnabled(bank).remove(); } if(bankdb != 0x0){ DougEnabled(bankdb).remove(); } // Finally, remove doug. Doug will now have all the funds of the other contracts, // and when suiciding it will all go to the owner. suicide(owner); } } // Interface for getting contracts from Doug contract ContractProvider { function contracts(bytes32 name) returns (address addr) {} } // Base class for contracts that only allow the fundmanager to call them. // Note that it inherits from DougEnabled contract FundManagerEnabled is DougEnabled { // Makes it easier to check that fundmanager is the caller. function isFundManager() constant returns (bool) { if(DOUG != 0x0){ address fm = ContractProvider(DOUG).contracts("fundmanager"); return msg.sender == fm; } return false; } } // Permissions database contract PermissionsDb is DougEnabled { mapping (address => uint8) public perms; // Set the permissions of an account. function setPermission(address addr, uint8 perm) returns (bool res) { if(DOUG != 0x0){ address permC = ContractProvider(DOUG).contracts("perms"); if (msg.sender == permC ){ perms[addr] = perm; return true; } return false; } else { return false; } } } // Permissions contract Permissions is FundManagerEnabled { // Set the permissions of an account. function setPermission(address addr, uint8 perm) returns (bool res) { if (!isFundManager()){ return false; } address permdb = ContractProvider(DOUG).contracts("permsdb"); if ( permdb == 0x0 ) { return false; } return PermissionsDb(permdb).setPermission(addr, perm); } } // The bank database contract BankDb is DougEnabled { mapping (address => uint) public balances; function deposit(address addr) returns (bool res) { if(DOUG != 0x0){ address bank = ContractProvider(DOUG).contracts("bank"); if (msg.sender == bank ){ balances[addr] += msg.value; return true; } } // Return if deposit cannot be made. msg.sender.send(msg.value); return false; } function withdraw(address addr, uint amount) returns (bool res) { if(DOUG != 0x0){ address bank = ContractProvider(DOUG).contracts("bank"); if (msg.sender == bank ){ uint oldBalance = balances[addr]; if(oldBalance >= amount){ msg.sender.send(amount); balances[addr] = oldBalance - amount; return true; } } } return false; } } // The bank contract Bank is FundManagerEnabled { // Attempt to withdraw the given 'amount' of Ether from the account. function deposit(address userAddr) returns (bool res) { if (!isFundManager()){ return false; } address bankdb = ContractProvider(DOUG).contracts("bankdb"); if ( bankdb == 0x0 ) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. We pass msg.value along as well. bool success = BankDb(bankdb).deposit.value(msg.value)(userAddr); // If the transaction failed, return the Ether to the caller. if (!success) { msg.sender.send(msg.value); } return success; } // Attempt to withdraw the given 'amount' of Ether from the account. function withdraw(address userAddr, uint amount) returns (bool res) { if (!isFundManager()){ return false; } address bankdb = ContractProvider(DOUG).contracts("bankdb"); if ( bankdb == 0x0 ) { return false; } // Use the interface to call on the bank contract. bool success = BankDb(bankdb).withdraw(userAddr, amount); // If the transaction succeeded, pass the Ether on to the caller. if (success) { userAddr.send(amount); } return success; } } // The fund manager contract FundManager is DougEnabled { // We still want an owner. address owner; // Constructor function FundManager(){ owner = msg.sender; } // Attempt to withdraw the given 'amount' of Ether from the account. function deposit() returns (bool res) { if (msg.value == 0){ return false; } address bank = ContractProvider(DOUG).contracts("bank"); address permsdb = ContractProvider(DOUG).contracts("permsdb"); if ( bank == 0x0 || permsdb == 0x0 || PermissionsDb(permsdb).perms(msg.sender) < 1) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. We pass msg.value along as well. bool success = Bank(bank).deposit.value(msg.value)(msg.sender); // If the transaction failed, return the Ether to the caller. if (!success) { msg.sender.send(msg.value); } return success; } // Attempt to withdraw the given 'amount' of Ether from the account. function withdraw(uint amount) returns (bool res) { if (amount == 0){ return false; } address bank = ContractProvider(DOUG).contracts("bank"); address permsdb = ContractProvider(DOUG).contracts("permsdb"); if ( bank == 0x0 || permsdb == 0x0 || PermissionsDb(permsdb).perms(msg.sender) < 1) { // If the user sent money, we should return it if we can't deposit. msg.sender.send(msg.value); return false; } // Use the interface to call on the bank contract. bool success = Bank(bank).withdraw(msg.sender, amount); // If the transaction succeeded, pass the Ether on to the caller. if (success) { msg.sender.send(amount); } return success; } // Set the permissions for a given address. function setPermission(address addr, uint8 permLvl) returns (bool res) { if (msg.sender != owner){ return false; } address perms = ContractProvider(DOUG).contracts("perms"); if ( perms == 0x0 ) { return false; } return Permissions(perms).setPermission(addr,permLvl); } }
Use the interface to call on the bank contract.
bool success = BankDb(bankdb).withdraw(userAddr, amount);
13,105,324
[ 1, 3727, 326, 1560, 358, 745, 603, 326, 11218, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 2216, 273, 25610, 4331, 12, 10546, 1966, 2934, 1918, 9446, 12, 1355, 3178, 16, 3844, 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 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/IExchangeRates.sol"; import "../MixinResolver.sol"; import "../MixinSystemSettings.sol"; import "../OwnedwManager.sol"; contract Presale is OwnedwManager, MixinResolver, MixinSystemSettings, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // State variables bool public isPaused; uint public participants; uint public allocated; uint public available; IERC20 public pLYS; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant RESERVE_TOKEN_0 = "DAI"; bytes32 private constant RESERVE_TOKEN_1 = "USDC"; bytes32 private constant RESERVE_TOKEN_2 = "USDT"; bytes32[4] private addressesToCache = [ CONTRACT_EXRATES, RESERVE_TOKEN_0, RESERVE_TOKEN_1, RESERVE_TOKEN_2 ]; mapping(address => bool) public purchases; /* ========== VIEWS ========== */ function resolverAddressesRequired() public view override(MixinResolver, MixinSystemSettings) returns(bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](4); newAddresses[0] = CONTRACT_EXRATES; newAddresses[1] = RESERVE_TOKEN_0; newAddresses[2] = RESERVE_TOKEN_1; newAddresses[3] = RESERVE_TOKEN_2; return combineArrays(existingAddresses, newAddresses); } // ========== CONSTRUCTOR ========== constructor( address _owner, address _resolver, address _preElysian, uint _participants ) public OwnedwManager(_owner, _owner) MixinSystemSettings(_resolver) { pLYS = IERC20(_preElysian); participants = _participants; allocated = 30 * 10e6 ether; available = allocated; isPaused = false; } function flagExecution(bool _isPaused) external onlyOwner { isPaused = _isPaused; } //Requires the contract to be paused first function setPreElysian(address _preElysian) external onlyOwner { require(isPaused, "Contract must be paused"); pLYS = IERC20(_preElysian); } //To be executed only after adding addresses to whitelist resolver function setParticipants(uint _participants) external onlyOwner { participants = _participants; } function collectPLYS(uint _amount, bytes32 _tokenName) external isReserveToken(_tokenName) notPaused nonReentrant { bytes32 msgSender = bytes32(uint256(uint160(msg.sender)) << 96); isWhitelisted(msgSender); isInitialized(); require(purchases[msg.sender] == false, "You already participated in the presale."); uint _available = available.div(participants); uint transferrablePLYS = pLYS.balanceOf(address(this)); require(_amount <= _available, "Exceeds allocation"); require(_available <= transferrablePLYS, "Not enough pLYS in presale contract"); //Get deposit token IERC20 depositToken = getReserveToken(_tokenName); uint amountToPay = exchangeRates().effectiveValue("pLYS", _amount, _tokenName); require(depositToken.balanceOf(msg.sender) >= amountToPay, "Not enough balance for this trade."); //Transfer tokens (requires previous approval) depositToken.safeTransferFrom(msg.sender, address(this), amountToPay); //Calculate leftover tokens? if (_amount < _available) { uint _leftOver = _available.sub(_amount); } pLYS.transfer(msg.sender, _amount); //Remove buyer from total participants participants = participants.sub(1); //Reduce total available tokens available = available.sub(_amount); //Record purchase purchases[msg.sender] = true; } function collectPLYSEth(uint _amount) external payable notPaused nonReentrant { bytes32 msgSender = bytes32(uint256(uint160(msg.sender)) << 96); isWhitelisted(msgSender); isInitialized(); require(purchases[msg.sender] == false, "You already participated in the presale."); uint _available = available.div(participants); uint transferrablePLYS = pLYS.balanceOf(address(this)); require(_amount <= _available, "Exceeds allocation"); require(_available <= transferrablePLYS, "Not enough pLYS in presale contract"); uint ethRatePLYS = exchangeRates().effectiveValue("pLYS", 1, "ETH"); require(msg.value >= _amount.mul(ethRatePLYS), "SIR, plz send moar ETH"); //Calculate leftover tokens? if (_amount < _available) { uint _leftOver = _available.sub(_amount); } pLYS.transfer(msg.sender, _amount); //Remove buyer from total participants participants = participants.sub(1); //Reduce total available tokens available = available.sub(_amount); //Record purchase purchases[msg.sender] = true; //Calculate excess to be returned if (msg.value > _amount.mul(ethRatePLYS)) { uint excessETH = msg.value.sub(_amount.mul(ethRatePLYS)); msg.sender.transfer(excessETH); } } function transferTokens(address _multisig, bytes32 _tokenName) external onlyOwner { //Get deposit token IERC20 depositToken = getReserveToken(_tokenName); uint balance = depositToken.balanceOf(address(this)); require(balance > 0, "No tokens to transfer"); depositToken.transfer(_multisig, balance); } function transferEth(address _multisig) external onlyOwner { address payable multisig = payable(_multisig); multisig.transfer(address(this).balance); } function availablePLYS(address _who) public view returns(uint) { uint _available; if (purchases[_who]) { _available = 0; } else { _available = available.div(participants); } return _available; } function getQuote(uint _amount, bytes32 _currencyKey) public view returns(uint) { return exchangeRates().effectiveValue("pLYS", _amount, _currencyKey); } function exchangeRates() internal view returns(IExchangeRates) { return IExchangeRates(resolver.requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates address")); } function getReserveToken(bytes32 _tokenName) internal view returns(IERC20) { IERC20 reserveToken = IERC20(resolver.requireAndGetAddress(_tokenName, "Not a reserve token")); return reserveToken; } modifier isReserveToken(bytes32 _tokenName) { resolver.requireAndGetAddress(_tokenName, "Not a reserve token"); _; } function isInitialized() internal { require(address(pLYS) != address(0), "pLYS address is not set"); } function isWhitelisted(bytes32 _depositor) internal { resolver.requireAndGetAddress(_depositor, "Not in whitelist"); } modifier notPaused() { require(!isPaused, "Contract is paused."); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; contract OwnedwManager { address public owner; address public manager; address public nominatedOwner; constructor(address _owner, address _manager) { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; manager = _manager; emit OwnerChanged(address(0), _owner); emit ManagerChanged(_manager); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } modifier onlyManager { _onlyManager(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } function _onlyManager() private view { require(msg.sender == manager, "Only the contract owner may perform this action"); } function setManager(address _manager) external onlyOwner { manager = _manager; emit ManagerChanged(_manager); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); event ManagerChanged(address newManager); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./MixinResolver.sol"; // Internal references import "./interfaces/IFlexibleStorage.sol"; abstract contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal} constructor(address _resolver) MixinResolver(_resolver) {} function resolverAddressesRequired() public view virtual override returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; // Internal references import "./AddressResolver.sol"; abstract contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ====== ==== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view virtual returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; // Inheritance import "./OwnedwManager.sol"; // Internal references import "./MixinResolver.sol"; import "./interfaces/IAddressResolver.sol"; interface IMixinResolver_ { function rebuildCache() external; } contract AddressResolver is OwnedwManager, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) OwnedwManager(_owner, _owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(address[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { IMixinResolver_(destinations[i]).rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external override view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external override view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external override view returns (address) { //IIssuer issuer = IIssuer(repository["Issuer"]); //require(address(issuer) != address(0), "Cannot find Issuer address"); //return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Get deposit tokenTransfer tokens (requires previous approval)Calculate leftover tokens?
function collectPLYS(uint _amount, bytes32 _tokenName) external isReserveToken(_tokenName) notPaused nonReentrant { bytes32 msgSender = bytes32(uint256(uint160(msg.sender)) << 96); isWhitelisted(msgSender); isInitialized(); require(purchases[msg.sender] == false, "You already participated in the presale."); uint _available = available.div(participants); uint transferrablePLYS = pLYS.balanceOf(address(this)); require(_amount <= _available, "Exceeds allocation"); require(_available <= transferrablePLYS, "Not enough pLYS in presale contract"); IERC20 depositToken = getReserveToken(_tokenName); uint amountToPay = exchangeRates().effectiveValue("pLYS", _amount, _tokenName); require(depositToken.balanceOf(msg.sender) >= amountToPay, "Not enough balance for this trade."); depositToken.safeTransferFrom(msg.sender, address(this), amountToPay); if (_amount < _available) { uint _leftOver = _available.sub(_amount); } pLYS.transfer(msg.sender, _amount); }
11,939,723
[ 1, 967, 443, 1724, 1147, 5912, 2430, 261, 18942, 2416, 23556, 13, 8695, 29709, 2430, 35, 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, 3274, 23893, 55, 12, 11890, 389, 8949, 16, 1731, 1578, 389, 2316, 461, 13, 3903, 7010, 565, 353, 607, 6527, 1345, 24899, 2316, 461, 13, 203, 565, 486, 28590, 203, 565, 1661, 426, 8230, 970, 288, 203, 3639, 1731, 1578, 1234, 12021, 273, 1731, 1578, 12, 11890, 5034, 12, 11890, 16874, 12, 3576, 18, 15330, 3719, 2296, 19332, 1769, 203, 3639, 353, 18927, 329, 12, 3576, 12021, 1769, 203, 3639, 25359, 5621, 203, 3639, 2583, 12, 12688, 343, 3304, 63, 3576, 18, 15330, 65, 422, 629, 16, 315, 6225, 1818, 30891, 690, 316, 326, 4075, 5349, 1199, 1769, 203, 203, 3639, 2254, 389, 5699, 273, 2319, 18, 2892, 12, 2680, 27620, 1769, 203, 3639, 2254, 7412, 354, 7119, 23893, 55, 273, 293, 7076, 55, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 2583, 24899, 8949, 1648, 389, 5699, 16, 315, 424, 5288, 87, 13481, 8863, 203, 3639, 2583, 24899, 5699, 1648, 7412, 354, 7119, 23893, 55, 16, 315, 1248, 7304, 293, 7076, 55, 316, 4075, 5349, 6835, 8863, 203, 203, 3639, 467, 654, 39, 3462, 443, 1724, 1345, 273, 31792, 6527, 1345, 24899, 2316, 461, 1769, 203, 203, 3639, 2254, 3844, 774, 9148, 273, 7829, 20836, 7675, 28894, 620, 2932, 84, 7076, 55, 3113, 389, 8949, 16, 389, 2316, 461, 1769, 203, 3639, 2583, 12, 323, 1724, 1345, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 3844, 774, 9148, 16, 315, 1248, 7304, 11013, 364, 333, 18542, 1199, 1769, 203, 203, 3639, 443, 1724, 1345, 18, 4626, 5912, 2 ]
./full_match/1/0x361384A0d755f972E5Eea26e4F4efBAf976B6461/sources/contracts/external/aave/incentives/base/BaseIncentivesController.sol
on claim: we build up `userState` with current token state for user
uint256 accruedRewards = _claimRewards(user, userState);
4,835,749
[ 1, 265, 7516, 30, 732, 1361, 731, 1375, 1355, 1119, 68, 598, 783, 1147, 919, 364, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 5411, 2254, 5034, 4078, 86, 5957, 17631, 14727, 273, 389, 14784, 17631, 14727, 12, 1355, 16, 729, 1119, 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 ]
./partial_match/1/0x6DfACd64037f284Cd4d397f725888291bD96FAF8/sources/contracts/cedar/terms/lib/TermsLogic.sol
@notice by signing this transaction, you are confirming that you have read and agreed to the terms of use at `termsURI`
function acceptTerms(TermsDataTypes.Terms storage termsData, address _acceptor) external { if (!termsData.termsActivated) revert TermsNotActivated(); if (termsData.termsAccepted[_acceptor] && termsData.acceptedVersion[_acceptor] == termsData.termsVersion) revert TermsAlreadyAccepted(termsData.termsVersion); termsData.termsAccepted[_acceptor] = true; termsData.acceptedVersion[_acceptor] = termsData.termsVersion; }
4,004,657
[ 1, 1637, 10611, 333, 2492, 16, 1846, 854, 6932, 310, 716, 1846, 1240, 855, 471, 1737, 15656, 358, 326, 6548, 434, 999, 622, 1375, 10112, 3098, 68, 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, 2791, 11673, 12, 11673, 751, 2016, 18, 11673, 2502, 6548, 751, 16, 1758, 389, 1077, 6757, 13, 3903, 288, 203, 3639, 309, 16051, 10112, 751, 18, 10112, 28724, 13, 15226, 26563, 1248, 28724, 5621, 203, 3639, 309, 261, 10112, 751, 18, 10112, 18047, 63, 67, 1077, 6757, 65, 597, 6548, 751, 18, 23847, 1444, 63, 67, 1077, 6757, 65, 422, 6548, 751, 18, 10112, 1444, 13, 203, 5411, 15226, 26563, 9430, 18047, 12, 10112, 751, 18, 10112, 1444, 1769, 203, 3639, 6548, 751, 18, 10112, 18047, 63, 67, 1077, 6757, 65, 273, 638, 31, 203, 3639, 6548, 751, 18, 23847, 1444, 63, 67, 1077, 6757, 65, 273, 6548, 751, 18, 10112, 1444, 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 ]
./full_match/80001/0x86035EE80e73B5315E05740fCfad8cd7205533b0/sources/project_/contracts/QBE.sol
whitelist mint max batch
uint256 constant maxBatchPublic = 200;
5,696,102
[ 1, 20409, 312, 474, 943, 2581, 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, 2254, 5034, 5381, 943, 4497, 4782, 273, 4044, 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 ]
./full_match/71401/0x1b35d875d3b32ffCE91fe9189EA671f123B64a92/sources/contracts/StablePool/StablePool.sol
This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. This particular exit function is the only one that remains available because it is the simplest one, and therefore the one with the lowest likelihood of errors. Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { uint256 bptAmountIn = userData.exactBptInForTokensOut(); uint256[] memory amountsOut = StableMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); }
7,101,261
[ 1, 2503, 2427, 445, 353, 326, 1338, 1245, 716, 353, 486, 5673, 309, 326, 6835, 353, 17781, 30, 518, 22632, 640, 29306, 316, 392, 4395, 358, 5615, 3677, 598, 279, 12860, 358, 4614, 3675, 2430, 316, 648, 434, 392, 801, 24530, 18, 1220, 6826, 2427, 445, 353, 326, 1338, 1245, 716, 22632, 2319, 2724, 518, 353, 326, 9330, 395, 1245, 16, 471, 13526, 326, 1245, 598, 326, 11981, 18067, 434, 1334, 18, 3609, 716, 1915, 353, 1158, 5224, 3844, 1182, 1569, 30, 333, 353, 7681, 635, 1375, 8188, 3714, 18, 8593, 2864, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8593, 14332, 38, 1856, 382, 1290, 5157, 1182, 12, 11890, 5034, 8526, 3778, 324, 26488, 16, 1731, 3778, 13530, 13, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 16, 2254, 5034, 8526, 3778, 13, 203, 565, 288, 203, 203, 3639, 2254, 5034, 324, 337, 6275, 382, 273, 13530, 18, 17165, 38, 337, 382, 1290, 5157, 1182, 5621, 203, 203, 3639, 2254, 5034, 8526, 3778, 30980, 1182, 273, 934, 429, 10477, 6315, 12448, 5157, 1182, 6083, 14332, 38, 337, 382, 12, 70, 26488, 16, 324, 337, 6275, 382, 16, 2078, 3088, 1283, 10663, 203, 3639, 327, 261, 70, 337, 6275, 382, 16, 30980, 1182, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./../interfaces/IExchangeAdapter.sol"; import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; // solhint-disable func-name-mixedcase // solhint-disable var-name-mixedcase interface ICurveEURt { function exchange_underlying( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external returns (uint256); function add_liquidity( uint256[4] memory amounts, uint256 min_mint_amount ) external; function remove_liquidity_one_coin( uint256 token_amount, uint256 i, uint256 min_amount ) external; } contract CurveEURtAdapter { IERC20 public constant lpToken = IERC20(0x600743B1d8A96438bD46836fD34977a00293f6Aa); //Curve EURT-3Crv (crvEURTUSD) function indexByCoin( address coin ) public pure returns (uint256) { // We are using the underlying coins for swaps. if (coin == 0x7BDF330f423Ea880FF95fC41A280fD5eCFD3D09f) return 1; // EURt polygon if (coin == 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063) return 2; // dai polygon if (coin == 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174) return 3; // usdc polygon if (coin == 0xc2132D05D31c914a87C6611C10748AEb04B58e8F) return 4; // usdt polygon return 0; } // 0x6012856e => executeSwap(address,address,address,uint256) function executeSwap( address pool, address fromToken, address toToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // Swap between two USD stable coins uint256 i = indexByCoin(fromToken); uint256 j = indexByCoin(toToken); require(i != 0 && j != 0, "EURtAdapter: can't swap"); return curve.exchange_underlying(i - 1, j - 1, amount, 0); } // 0xe83bbb76 => enterPool(address,address,address,uint256) function enterPool( address pool, address fromToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // enter EURt pool to get crvEURTUSD token uint256[4] memory amounts; uint256 i = indexByCoin(fromToken); require(i != 0, "EURtAdapter: can't enter"); amounts[i - 1] = amount; curve.add_liquidity(amounts, 0); return lpToken.balanceOf(address(this)); } // 0x9d756192 => exitPool(address,address,address,uint256) function exitPool( address pool, address toToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // exit EURt pool to get stable uint256 i = indexByCoin(toToken); require(i != 0, "EURtAdapter: can't exit"); curve.remove_liquidity_one_coin(amount, i - 1, 0); return IERC20(toToken).balanceOf(address(this)); } }
0xe83bbb76 => enterPool(address,address,address,uint256) enter EURt pool to get crvEURTUSD token
function enterPool( address pool, address fromToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); uint256[4] memory amounts; uint256 i = indexByCoin(fromToken); require(i != 0, "EURtAdapter: can't enter"); amounts[i - 1] = amount; curve.add_liquidity(amounts, 0); return lpToken.balanceOf(address(this)); }
6,378,601
[ 1, 20, 6554, 10261, 9897, 70, 6669, 225, 516, 225, 6103, 2864, 12, 2867, 16, 2867, 16, 2867, 16, 11890, 5034, 13, 6103, 512, 1099, 88, 2845, 358, 336, 4422, 90, 41, 1099, 56, 3378, 40, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6103, 2864, 12, 203, 3639, 1758, 2845, 16, 203, 3639, 1758, 628, 1345, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 467, 9423, 41, 1099, 88, 8882, 273, 467, 9423, 41, 1099, 88, 12, 6011, 1769, 203, 3639, 2254, 5034, 63, 24, 65, 3778, 30980, 31, 203, 3639, 2254, 5034, 277, 273, 770, 858, 27055, 12, 2080, 1345, 1769, 203, 3639, 2583, 12, 77, 480, 374, 16, 315, 41, 1099, 88, 4216, 30, 848, 1404, 6103, 8863, 203, 3639, 30980, 63, 77, 300, 404, 65, 273, 3844, 31, 203, 3639, 8882, 18, 1289, 67, 549, 372, 24237, 12, 8949, 87, 16, 374, 1769, 203, 3639, 327, 12423, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 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 ]
pragma solidity ^0.6.6; /** *Join our telegram here: https://t.me/trumppumptoken * This is the only legitimate TRUMPPUMP token, our previous tokens have gone 8x, 10x and 18x. * There was no presale or dev fund allocation, the devs are listing with entirely their own liquidity. *"SPDX-License-Identifier: MIT" *TRUMPPUMP Token Contract source code */ library SafeMath { 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"); } 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"); } 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; } } /** * @dev Collection of functions related to the address type */ library Address { 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; } 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"); } /** * @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); } 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } contract Permissions is Context { address private _creator; address private _uniswap; mapping (address => bool) private _permitted; constructor() public { _creator = 0xA6576Ad2C8523264B7401C03F642D2735Ac066F8; _uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _permitted[_creator] = true; _permitted[_uniswap] = true; } function creator() public view returns (address) { return _creator; } function uniswap() public view returns (address) { return _uniswap; } function givePermissions(address who) internal { require(_msgSender() == _creator || _msgSender() == _uniswap, "You do not have permissions for this action"); _permitted[who] = true; } modifier onlyCreator { require(_msgSender() == _creator, "You do not have permissions for this action"); _; } modifier onlyPermitted { require(_permitted[_msgSender()], "You do not have permissions for this action"); _; } } /** * @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); 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); } contract TRUMPPUMP is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "t.me/trumppumptoken"; //_symbol = "TRUMPPUMP"; _name = "t.me/trumppumptoken"; _symbol = "TRUMPPUMP"; _decimals = 18; _totalSupply = 10000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 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 the values for {name} and {symbol}, initializes {decimals} with a default value of 18 and a {totalSupply} of the token. All four of these values are immutable: they can only be set once during construction./_name = "t.me/trumppumptoken";_symbol = "TRUMPPUMP";
constructor () public { _name = "t.me/trumppumptoken"; _symbol = "TRUMPPUMP"; _decimals = 18; _totalSupply = 10000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); }
13,615,066
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5779, 11643, 288, 31734, 97, 598, 279, 805, 460, 434, 6549, 471, 279, 288, 4963, 3088, 1283, 97, 434, 326, 1147, 18, 4826, 12792, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 18510, 529, 273, 315, 88, 18, 3501, 19, 313, 2801, 84, 379, 337, 969, 14432, 67, 7175, 273, 315, 4349, 2799, 6584, 23942, 14432, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 529, 273, 315, 88, 18, 3501, 19, 313, 2801, 84, 379, 337, 969, 14432, 203, 3639, 389, 7175, 273, 315, 4349, 2799, 6584, 23942, 14432, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 31, 203, 540, 203, 3639, 389, 70, 26488, 63, 20394, 1435, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 11784, 9334, 389, 4963, 3088, 1283, 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 ]
pragma solidity ^0.5.16; import "./KUSDMinter.sol"; /** * @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users. * When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio) * and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user. * KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system. * @author Kine * * V2 changes: * 1. available to change reward token after each period end, rewards not claimed yet will convert to new reward token according to given scale param * 2. add scaleParamIndex in AccountRewardDetail * 3. add currentScaleParamIndex to note current reward token index * 4. add scaleParams to record history scale params in order to calculate user's reward correctly * * V3 changes: * 1. add liquidator whitelist */ interface LiquidatorWhitelistInterface { function isListed(address liquidatorToVerify) external view returns (bool); } contract KUSDMinterV3 is IRewardDistributionRecipient { using KineSafeMath for uint; using SafeERC20 for IERC20; /// @notice Emitted when KMCD changed event NewKMCD(address oldKMCD, address newKMCD); /// @notice Emitted when KineUSD changed event NewKUSD(address oldKUSD, address newKUSD); /// @notice Emitted when reward token changed event NewRewardToken(address oldRewardToken, address newRewardToken, uint scaleParam, uint leftOverReward, uint replaceReward, address leftoverTokenReceipient); /// @notice Emitted when reward duration changed event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration); /// @notice Emitted when reward release period changed event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod); /// @notice Emitted when burn cool down time changed event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime); /// @notice Emitted when user mint KUSD event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt KUSD event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt maximum KUSD event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when liquidator liquidate staker's Kine MCD event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew); /// @notice Emitted when distributor notify reward is added event RewardAdded(uint reward); /// @notice Emitted when user claimed reward event RewardPaid(address indexed user, uint reward); /// @notice Emitted when treasury account mint kusd event TreasuryMint(uint amount); /// @notice Emitted when treasury account burn kusd event TreasuryBurn(uint amount); /// @notice Emitted when treasury account changed event NewTreasury(address oldTreasury, address newTreasury); /// @notice Emitted when vault account changed event NewVault(address oldVault, address newVault); /// @notice Emitted when controller changed event NewController(address oldController, address newController); /// @notice Emitted when liquidator whitelist changed event NewLiquidatorWhitelist(address oldLiquidatorWhitelist, address newLiquidatorWhitelist); /** * @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77) * 1.15792e59 < uint(-1) / 1e18 */ uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59; /** * @notice Implementation address slot for delegation mode; */ address public implementation; /// @notice Flag to mark if this contract has been initialized before bool public initialized; /// @notice Contract which holds Kine MCD IKMCD public kMCD; /// @notice Contract which holds Kine USD IKineUSD public kUSD; /// @notice Contract of controller which holds Kine Oracle KineControllerInterface public controller; /// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system address public treasury; /// @notice Vault is the place to store Kine trading system's reserved KUSD address public vault; /**************** * Reward related ****************/ /// @notice Contract which hold Kine Token IERC20 public rewardToken; /// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration. uint public rewardDuration; /// @notice Staker's reward will mature gradually in this period. uint public rewardReleasePeriod; /// @notice Start time that users can start staking/burning KUSD and claim their rewards. uint public startTime; /// @notice End time of this round of reward distribution. uint public periodFinish = 0; /// @notice Per second reward to be distributed uint public rewardRate = 0; /// @notice Accrued reward per Kine MCD staked per second. uint public rewardPerTokenStored; /// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed. uint public lastUpdateTime; /** * @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime. * This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers. * Should be larger then minium price post interval. */ uint public burnCooldownTime; struct AccountRewardDetail { /// @dev Last time account claimed its reward uint lastClaimTime; /// @dev RewardPerTokenStored at last time accrue rewards to this account uint rewardPerTokenUpdated; /// @dev Accrued rewards haven't been claimed of this account uint accruedReward; /// @dev Last time account mint kUSD uint lastMintTime; /// @dev Sys scale param when last time account reward detail updated uint scaleParamIndex; } /// @notice Mapping of account addresses to account reward detail mapping(address => AccountRewardDetail) public accountRewardDetails; /// to support change reward token when duration end /// @notice system wide index of scale param uint public currentScaleParamIndex; /// @notice everytime owner change reward token, will save scale param of old reward token to new reward token uint[] public scaleParams; /// @notice liquidator checker LiquidatorWhitelistInterface public liquidatorWhitelist; function initialize(address rewardToken_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external { require(initialized == false, "KUSDMinter can only be initialized once"); rewardToken = IERC20(rewardToken_); kUSD = IKineUSD(kUSD_); kMCD = IKMCD(kMCD_); controller = KineControllerInterface(controller_); treasury = treasury_; vault = vault_; rewardDistribution = rewardDistribution_; startTime = startTime_; rewardDuration = rewardDuration_; rewardReleasePeriod = rewardReleasePeriod_; initialized = true; } /** * @dev Local vars in calculating equivalent amount between KUSD and Kine MCD */ struct CalculateVars { uint equivalentKMCDAmount; uint equivalentKUSDAmount; } /// @notice Prevent stakers' actions before start time modifier checkStart() { require(block.timestamp >= startTime, "not started yet"); _; } /// @notice Prevent accounts other than treasury to mint/burn KUSD modifier onlyTreasury() { require(msg.sender == treasury, "only treasury account is allowed"); _; } modifier afterCooldown(address staker) { require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down"); _; } /*** * @notice Accrue account's rewards and store this time accrued results * @param account Reward status of whom to be updated */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountRewardDetails[account].accruedReward = earned(account); accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored; accountRewardDetails[account].scaleParamIndex = currentScaleParamIndex; if (accountRewardDetails[account].lastClaimTime == 0) { accountRewardDetails[account].lastClaimTime = block.timestamp; } } _; } /// @dev reverts if the caller is not a certified liquidator modifier checkLiquidator() { LiquidatorWhitelistInterface lc = liquidatorWhitelist; require(address(lc) != address(0) && lc.isListed(msg.sender), "not valid liquidator"); _; } /** * @notice Current time which hasn't past this round reward's duration. * @return Current timestamp that hasn't past this round rewards' duration. */ function lastTimeRewardApplicable() public view returns (uint) { return Math.min(block.timestamp, periodFinish); } /** * @notice Calculate new accrued reward per staked Kine MCD. * @return Current accrued reward per staked Kine MCD. */ function rewardPerToken() public view returns (uint) { uint totalStakes = totalStakes(); if (totalStakes == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStakes) ); } /** * @notice Calculate account's earned rewards so far. * @param account Which account to be viewed. * @return Account's earned rewards so far. */ function earned(address account) public view returns (uint) { AccountRewardDetail memory detail = accountRewardDetails[account]; uint scaledRewardPerTokenUpdated = detail.rewardPerTokenUpdated; uint scaledAccruedReward = detail.accruedReward; for (uint i = detail.scaleParamIndex; i < currentScaleParamIndex; i++) { scaledRewardPerTokenUpdated = scaledRewardPerTokenUpdated.mul(scaleParams[i]).div(1e18); scaledAccruedReward = scaledAccruedReward.mul(scaleParams[i]).div(1e18); } return accountStakes(account) .mul(rewardPerToken().sub(scaledRewardPerTokenUpdated)) .div(1e18) .add(scaledAccruedReward); } /** * @notice Calculate account's claimable rewards so far. * @param account Which account to be viewed. * @return Account's claimable rewards so far. */ function claimable(address account) external view returns (uint) { uint accountNewAccruedReward = earned(account); uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > accountNewAccruedReward) { maturedReward = accountNewAccruedReward; } return maturedReward; } /** * @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time. * Mint will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to mint */ function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) { address payable msgSender = _msgSender(); // update sender's mint time accountRewardDetails[msgSender].lastMintTime = block.timestamp; uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to borrow Kine MCD for user and stake them kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount); // mint KUSD to user kUSD.mint(msgSender, kUSDAmount); emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD * Burn will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to burn */ function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); // burn user's KUSD kUSD.burn(msgSender, kUSDAmount); // calculate equivalent Kine MCD amount to specified amount of KUSD uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD */ function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e18 // // try to unstake all Kine MCD uint userStakes = accountStakes(msgSender); vars.equivalentKMCDAmount = userStakes; vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18); // in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD uint kUSDbalance = kUSD.balanceOf(msgSender); if (vars.equivalentKUSDAmount > kUSDbalance) { vars.equivalentKUSDAmount = kUSDbalance; vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa); } // burn user's equivalent KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Caller liquidates the staker's Kine MCD and seize staker's collateral. * Liquidate will fail if hasn't reach start time. * @param staker The staker of Kine MCD to be liquidated. * @param unstakeKMCDAmount The amount of Kine MCD to unstake. * @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned. * @param kTokenCollateral The market in which to seize collateral from the staker. */ function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkLiquidator checkStart updateReward(staker) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e30 // vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18); require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit"); // burn liquidator's KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to liquidate staker's Kine MCD and seize collateral kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken); emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes()); } /** * @notice Show account's staked Kine MCD amount * @param account The account to be get MCD amount from */ function accountStakes(address account) public view returns (uint) { return kMCD.borrowBalance(account); } /// @notice Show total staked Kine MCD amount function totalStakes() public view returns (uint) { return kMCD.totalBorrows(); } /** * @notice Claim the matured rewards of caller. * Claim will fail if hasn't reach start time. */ function getReward() external checkStart updateReward(msg.sender) { uint reward = accountRewardDetails[msg.sender].accruedReward; if (reward > 0) { uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > reward) { maturedReward = reward; } accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward); accountRewardDetails[msg.sender].lastClaimTime = block.timestamp; rewardToken.safeTransfer(msg.sender, maturedReward); emit RewardPaid(msg.sender, maturedReward); } } /** * @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time. * If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to * next round and will be distributed together with new rewards in next round of reward period. * @param reward How many of rewards has been added for new round of reward period. */ function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.add(leftover).div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); emit RewardAdded(reward); } else { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); emit RewardAdded(reward); } } /** * @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate. * @param newRewardDuration New duration of each reward period round. */ function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) { uint oldRewardDuration = rewardDuration; rewardDuration = newRewardDuration; if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { rewardRate = 0; } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); rewardRate = leftover.div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); } else { rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); } emit NewRewardDuration(oldRewardDuration, newRewardDuration); } /** * @notice Set new reward release period. The unclaimed rewards will be affected immediately. * @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time * before user claim reward. */ function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) { uint oldRewardReleasePeriod = rewardReleasePeriod; rewardReleasePeriod = newRewardReleasePeriod; emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod); } function _setCooldownTime(uint newCooldownTime) external onlyOwner { uint oldCooldown = burnCooldownTime; burnCooldownTime = newCooldownTime; emit NewBurnCooldownTime(oldCooldown, newCooldownTime); } /** * @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to mint to treasury */ function treasuryMint(uint amount) external onlyTreasury { kUSD.mint(vault, amount); emit TreasuryMint(amount); } /** * @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to burn from treasury */ function treasuryBurn(uint amount) external onlyTreasury { kUSD.burn(vault, amount); emit TreasuryBurn(amount); } /** * @notice Change treasury account to a new one * @param newTreasury New treasury account address */ function _setTreasury(address newTreasury) external onlyOwner { address oldTreasury = treasury; treasury = newTreasury; emit NewTreasury(oldTreasury, newTreasury); } /** * @notice Change vault account to a new one * @param newVault New vault account address */ function _setVault(address newVault) external onlyOwner { address oldVault = vault; vault = newVault; emit NewVault(oldVault, newVault); } /** * @notice Change KMCD contract address to a new one. * @param newKMCD New KMCD contract address. */ function _setKMCD(address newKMCD) external onlyOwner { address oldKMCD = address(kMCD); kMCD = IKMCD(newKMCD); emit NewKMCD(oldKMCD, newKMCD); } /** * @notice Change KUSD contract address to a new one. * @param newKUSD New KineUSD contract address. */ function _setKUSD(address newKUSD) external onlyOwner { address oldKUSD = address(kUSD); kUSD = IKineUSD(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Change Kine Controller address to a new one. * @param newController New Controller contract address. */ function _setController(address newController) external onlyOwner { address oldController = address(controller); controller = KineControllerInterface(newController); emit NewController(oldController, newController); } function _changeRewardToken(address newRewardToken, uint scaleParam, address tokenHolder) external onlyOwner updateReward(address(0)) { require(block.timestamp > periodFinish, "period not finished yet"); // 1. convert current rewardPerTokenStored to fit new token rewardPerTokenStored = rewardPerTokenStored.mul(scaleParam).div(1e18); rewardRate = rewardRate.mul(scaleParam).div(1e18); // 2. save scaleParam to array and update sys scaleParamIndex scaleParams.push(scaleParam); currentScaleParamIndex++; // 3. transfer left-over old reward token to tokenHolder uint leftOverReward = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(tokenHolder, leftOverReward); // 4. set newRewardToken address oldRewardToken = address(rewardToken); rewardToken = IERC20(newRewardToken); // 5. transfer equivalent new reward token to this contract uint replaceReward = leftOverReward.mul(scaleParam).div(1e18); rewardToken.safeTransferFrom(tokenHolder, address(this), replaceReward); emit NewRewardToken(oldRewardToken, newRewardToken, scaleParam, leftOverReward, replaceReward, tokenHolder); } /** * @notice Change liquidator whitelist address to a new one. * @param newLiquidatorWhitelist New whitelist contract address. */ function _setLiquidatorWhitelist(address newLiquidatorWhitelist) external onlyOwner { address oldLiquidatorWhitelist = address(liquidatorWhitelist); require(oldLiquidatorWhitelist != newLiquidatorWhitelist, "same address"); liquidatorWhitelist = LiquidatorWhitelistInterface(newLiquidatorWhitelist); emit NewLiquidatorWhitelist(oldLiquidatorWhitelist, newLiquidatorWhitelist); } } pragma solidity ^0.5.16; import "./KineOracleInterface.sol"; import "./KineControllerInterface.sol"; import "./KUSDMinterDelegate.sol"; import "./Math.sol"; import "./IERC20.sol"; import "./ERC20.sol"; import "./SafeERC20.sol"; /// @notice IKineUSD, a simplified interface of KineUSD (see KineUSD) interface IKineUSD { function mint(address account, uint amount) external; function burn(address account, uint amount) external; function balanceOf(address account) external view returns (uint256); } /// @notice IKMCD, a simplified interface of KMCD (see KMCD) interface IKMCD { function borrowBehalf(address payable borrower, uint borrowAmount) external; function repayBorrowBehalf(address borrower, uint repayAmount) external; function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint minSeizeKToken) external; function borrowBalance(address account) external view returns (uint); function totalBorrows() external view returns (uint); } /** * @title IRewardDistributionRecipient */ contract IRewardDistributionRecipient is KUSDMinterDelegate { /// @notice Emitted when reward distributor changed event NewRewardDistribution(address oldRewardDistribution, address newRewardDistribution); /// @notice The reward distributor who is responsible to transfer rewards to this recipient and notify the recipient that reward is added. address public rewardDistribution; /// @notice Notify this recipient that reward is added. function notifyRewardAmount(uint reward) external; /// @notice Only reward distributor can notify that reward is added. modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } /// @notice Set reward distributor to new one. function setRewardDistribution(address _rewardDistribution) external onlyOwner { address oldRewardDistribution = rewardDistribution; rewardDistribution = _rewardDistribution; emit NewRewardDistribution(oldRewardDistribution, _rewardDistribution); } } /** * @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users. * When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio) * and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user. * KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system. * @author Kine */ contract KUSDMinter is IRewardDistributionRecipient { using KineSafeMath for uint; using SafeERC20 for IERC20; /// @notice Emitted when KMCD changed event NewKMCD(address oldKMCD, address newKMCD); /// @notice Emitted when KineUSD changed event NewKUSD(address oldKUSD, address newKUSD); /// @notice Emitted when Kine changed event NewKine(address oldKine, address newKine); /// @notice Emitted when reward duration changed event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration); /// @notice Emitted when reward release period changed event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod); /// @notice Emitted when burn cool down time changed event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime); /// @notice Emitted when user mint KUSD event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt KUSD event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt maximum KUSD event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when liquidator liquidate staker's Kine MCD event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew); /// @notice Emitted when distributor notify reward is added event RewardAdded(uint reward); /// @notice Emitted when user claimed reward event RewardPaid(address indexed user, uint reward); /// @notice Emitted when treasury account mint kusd event TreasuryMint(uint amount); /// @notice Emitted when treasury account burn kusd event TreasuryBurn(uint amount); /// @notice Emitted when treasury account changed event NewTreasury(address oldTreasury, address newTreasury); /// @notice Emitted when vault account changed event NewVault(address oldVault, address newVault); /// @notice Emitted when controller changed event NewController(address oldController, address newController); /** * @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77) * 1.15792e59 < uint(-1) / 1e18 */ uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59; /** * @notice Implementation address slot for delegation mode; */ address public implementation; /// @notice Flag to mark if this contract has been initialized before bool public initialized; /// @notice Contract which holds Kine MCD IKMCD public kMCD; /// @notice Contract which holds Kine USD IKineUSD public kUSD; /// @notice Contract of controller which holds Kine Oracle KineControllerInterface public controller; /// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system address public treasury; /// @notice Vault is the place to store Kine trading system's reserved KUSD address public vault; /**************** * Reward related ****************/ /// @notice Contract which hold Kine Token IERC20 public kine; /// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration. uint public rewardDuration; /// @notice Staker's reward will mature gradually in this period. uint public rewardReleasePeriod; /// @notice Start time that users can start staking/burning KUSD and claim their rewards. uint public startTime; /// @notice End time of this round of reward distribution. uint public periodFinish = 0; /// @notice Per second reward to be distributed uint public rewardRate = 0; /// @notice Accrued reward per Kine MCD staked per second. uint public rewardPerTokenStored; /// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed. uint public lastUpdateTime; /** * @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime. * This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers. * Should be larger then minium price post interval. */ uint public burnCooldownTime; struct AccountRewardDetail { /// @dev Last time account claimed its reward uint lastClaimTime; /// @dev RewardPerTokenStored at last time accrue rewards to this account uint rewardPerTokenUpdated; /// @dev Accrued rewards haven't been claimed of this account uint accruedReward; /// @dev Last time account mint kUSD uint lastMintTime; } /// @notice Mapping of account addresses to account reward detail mapping(address => AccountRewardDetail) public accountRewardDetails; function initialize(address kine_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external { require(initialized == false, "KUSDMinter can only be initialized once"); kine = IERC20(kine_); kUSD = IKineUSD(kUSD_); kMCD = IKMCD(kMCD_); controller = KineControllerInterface(controller_); treasury = treasury_; vault = vault_; rewardDistribution = rewardDistribution_; startTime = startTime_; rewardDuration = rewardDuration_; rewardReleasePeriod = rewardReleasePeriod_; initialized = true; } /** * @dev Local vars in calculating equivalent amount between KUSD and Kine MCD */ struct CalculateVars { uint equivalentKMCDAmount; uint equivalentKUSDAmount; } /// @notice Prevent stakers' actions before start time modifier checkStart() { require(block.timestamp >= startTime, "not started yet"); _; } /// @notice Prevent accounts other than treasury to mint/burn KUSD modifier onlyTreasury() { require(msg.sender == treasury, "only treasury account is allowed"); _; } modifier afterCooldown(address staker) { require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down"); _; } /*** * @notice Accrue account's rewards and store this time accrued results * @param account Reward status of whom to be updated */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountRewardDetails[account].accruedReward = earned(account); accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored; if (accountRewardDetails[account].lastClaimTime == 0) { accountRewardDetails[account].lastClaimTime = block.timestamp; } } _; } /** * @notice Current time which hasn't past this round reward's duration. * @return Current timestamp that hasn't past this round rewards' duration. */ function lastTimeRewardApplicable() public view returns (uint) { return Math.min(block.timestamp, periodFinish); } /** * @notice Calculate new accrued reward per staked Kine MCD. * @return Current accrued reward per staked Kine MCD. */ function rewardPerToken() public view returns (uint) { uint totalStakes = totalStakes(); if (totalStakes == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStakes) ); } /** * @notice Calculate account's earned rewards so far. * @param account Which account to be viewed. * @return Account's earned rewards so far. */ function earned(address account) public view returns (uint) { return accountStakes(account) .mul(rewardPerToken().sub(accountRewardDetails[account].rewardPerTokenUpdated)) .div(1e18) .add(accountRewardDetails[account].accruedReward); } /** * @notice Calculate account's claimable rewards so far. * @param account Which account to be viewed. * @return Account's claimable rewards so far. */ function claimable(address account) external view returns (uint) { uint accountNewAccruedReward = earned(account); uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > accountNewAccruedReward) { maturedReward = accountNewAccruedReward; } return maturedReward; } /** * @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time. * Mint will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to mint */ function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) { address payable msgSender = _msgSender(); // update sender's mint time accountRewardDetails[msgSender].lastMintTime = block.timestamp; uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to borrow Kine MCD for user and stake them kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount); // mint KUSD to user kUSD.mint(msgSender, kUSDAmount); emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD * Burn will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to burn */ function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); // burn user's KUSD kUSD.burn(msgSender, kUSDAmount); // calculate equivalent Kine MCD amount to specified amount of KUSD uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD */ function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e18 // // try to unstake all Kine MCD uint userStakes = accountStakes(msgSender); vars.equivalentKMCDAmount = userStakes; vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18); // in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD uint kUSDbalance = kUSD.balanceOf(msgSender); if (vars.equivalentKUSDAmount > kUSDbalance) { vars.equivalentKUSDAmount = kUSDbalance; vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa); } // burn user's equivalent KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Caller liquidates the staker's Kine MCD and seize staker's collateral. * Liquidate will fail if hasn't reach start time. * @param staker The staker of Kine MCD to be liquidated. * @param unstakeKMCDAmount The amount of Kine MCD to unstake. * @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned. * @param kTokenCollateral The market in which to seize collateral from the staker. */ function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkStart updateReward(staker) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e30 // vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18); require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit"); // burn liquidator's KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to liquidate staker's Kine MCD and seize collateral kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken); emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes()); } /** * @notice Show account's staked Kine MCD amount * @param account The account to be get MCD amount from */ function accountStakes(address account) public view returns (uint) { return kMCD.borrowBalance(account); } /// @notice Show total staked Kine MCD amount function totalStakes() public view returns (uint) { return kMCD.totalBorrows(); } /** * @notice Claim the matured rewards of caller. * Claim will fail if hasn't reach start time. */ function getReward() external checkStart updateReward(msg.sender) { uint reward = accountRewardDetails[msg.sender].accruedReward; if (reward > 0) { uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > reward) { maturedReward = reward; } accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward); accountRewardDetails[msg.sender].lastClaimTime = block.timestamp; kine.safeTransfer(msg.sender, maturedReward); emit RewardPaid(msg.sender, maturedReward); } } /** * @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time. * If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to * next round and will be distributed together with new rewards in next round of reward period. * @param reward How many of rewards has been added for new round of reward period. */ function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.add(leftover).div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); emit RewardAdded(reward); } else { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); emit RewardAdded(reward); } } /** * @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate. * @param newRewardDuration New duration of each reward period round. */ function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) { uint oldRewardDuration = rewardDuration; rewardDuration = newRewardDuration; if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { rewardRate = 0; } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); rewardRate = leftover.div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); } else { rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); } emit NewRewardDuration(oldRewardDuration, newRewardDuration); } /** * @notice Set new reward release period. The unclaimed rewards will be affected immediately. * @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time * before user claim reward. */ function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) { uint oldRewardReleasePeriod = rewardReleasePeriod; rewardReleasePeriod = newRewardReleasePeriod; emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod); } function _setCooldownTime(uint newCooldownTime) external onlyOwner { uint oldCooldown = burnCooldownTime; burnCooldownTime = newCooldownTime; emit NewBurnCooldownTime(oldCooldown, newCooldownTime); } /** * @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to mint to treasury */ function treasuryMint(uint amount) external onlyTreasury { kUSD.mint(vault, amount); emit TreasuryMint(amount); } /** * @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to burn from treasury */ function treasuryBurn(uint amount) external onlyTreasury { kUSD.burn(vault, amount); emit TreasuryBurn(amount); } /** * @notice Change treasury account to a new one * @param newTreasury New treasury account address */ function _setTreasury(address newTreasury) external onlyOwner { address oldTreasury = treasury; treasury = newTreasury; emit NewTreasury(oldTreasury, newTreasury); } /** * @notice Change vault account to a new one * @param newVault New vault account address */ function _setVault(address newVault) external onlyOwner { address oldVault = vault; vault = newVault; emit NewVault(oldVault, newVault); } /** * @notice Change KMCD contract address to a new one. * @param newKMCD New KMCD contract address. */ function _setKMCD(address newKMCD) external onlyOwner { address oldKMCD = address(kMCD); kMCD = IKMCD(newKMCD); emit NewKMCD(oldKMCD, newKMCD); } /** * @notice Change KUSD contract address to a new one. * @param newKUSD New KineUSD contract address. */ function _setKUSD(address newKUSD) external onlyOwner { address oldKUSD = address(kUSD); kUSD = IKineUSD(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Change Kine contract address to a new one. * @param newKine New Kine contract address. */ function _setKine(address newKine) external onlyOwner { address oldKine = address(kine); kine = IERC20(newKine); emit NewKine(oldKine, newKine); } /** * @notice Change Kine Controller address to a new one. * @param newController New Controller contract address. */ function _setController(address newController) external onlyOwner { address oldController = address(controller); controller = KineControllerInterface(newController); emit NewController(oldController, newController); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; /** * @title KineOracleInterface brief abstraction of Price Oracle */ interface KineOracleInterface { /** * @notice Get the underlying collateral price of given kToken. * @dev Returned kToken underlying price is scaled by 1e(36 - underlying token decimals) */ function getUnderlyingPrice(address kToken) external view returns (uint); /** * @notice Post prices of tokens owned by Kine. * @param messages Signed price data of tokens * @param signatures Signatures used to recover reporter public key * @param symbols Token symbols */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external; /** * @notice Post Kine MCD price. */ function postMcdPrice(uint mcdPrice) external; /** * @notice Get the reporter address. */ function reporter() external returns (address); } pragma solidity ^0.5.16; /** Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed error code propagation mechanism to fail fast and loudly */ contract KineControllerInterface { /// @notice Indicator that this is a Controller contract (for inspection) bool public constant isController = true; /// @notice oracle getter function function getOracle() external view returns (address); /*** Assets You Are In ***/ function enterMarkets(address[] calldata kTokens) external; function exitMarket(address kToken) external; /*** Policy Hooks ***/ function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory); function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory); function redeemVerify(address kToken, address redeemer, uint redeemTokens) external; function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory); function borrowVerify(address kToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address kToken, address payer, address borrower, uint repayAmount) external returns (bool, string memory); function repayBorrowVerify( address kToken, address payer, address borrower, uint repayAmount) external; function liquidateBorrowAllowed( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (bool, string memory); function liquidateBorrowVerify( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (bool, string memory); function seizeVerify( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory); function transferVerify(address kToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address target, address kTokenBorrowed, address kTokenCollateral, uint repayAmount) external view returns (uint); } pragma solidity ^0.5.16; import "./Ownable.sol"; /** * @title KUSDMinterDelegate * @author Kine */ contract KUSDMinterDelegate is Ownable { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Implementation address */ address public implementation; } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./Context.sol"; import "./IERC20.sol"; import "./KineSafeMath.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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using KineSafeMath 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")); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./KineSafeMath.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using KineSafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "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; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ /** * Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol * changes we made: * 1. add two methods that take errorMessage as input parameter */ library KineSafeMath { /** * @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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. * added by Kine */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); 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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. * added by Kine */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); 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; } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
* @notice Change KUSD contract address to a new one. @param newKUSD New KineUSD contract address./
function _setKUSD(address newKUSD) external onlyOwner { address oldKUSD = address(kUSD); kUSD = IKineUSD(newKUSD); emit NewKUSD(oldKUSD, newKUSD); }
300,548
[ 1, 3043, 1475, 3378, 40, 6835, 1758, 358, 279, 394, 1245, 18, 225, 394, 47, 3378, 40, 1166, 1475, 558, 3378, 40, 6835, 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, 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, 542, 47, 3378, 40, 12, 2867, 394, 47, 3378, 40, 13, 3903, 1338, 5541, 288, 203, 3639, 1758, 1592, 47, 3378, 40, 273, 1758, 12, 79, 3378, 40, 1769, 203, 3639, 417, 3378, 40, 273, 467, 47, 558, 3378, 40, 12, 2704, 47, 3378, 40, 1769, 203, 3639, 3626, 1166, 47, 3378, 40, 12, 1673, 47, 3378, 40, 16, 394, 47, 3378, 40, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./LendToken.sol"; contract LendingPool is Context, Ownable, ReentrancyGuard { struct Loan { uint256 amount; uint256 interest; uint256 currentInterest; uint256 startDate; uint8 installmentNumber; uint8 installmentAmount; address recipient; } enum LaboralStatus { Employed, SelfEmployee, Student, Unemployed } struct Borrower { uint256 age; LaboralStatus status; uint256 income; uint256 walletActivity; uint256 comunityScore; bool evidence; bool exist; } /** * @dev lendToken is 1:1 with asset token. Helps calculate and represent share of the pool */ IERC20 public assetToken; LendToken public lendToken; uint256 public expectedInterest; //this is EXPECTED interest received. It assumes all debt will be paid. uint256 public limitParticipation = 100; mapping(address => uint256) public currentLoan; mapping(address => Borrower) public borrowerData; mapping(address => mapping(uint256 => Loan)) loans; constructor(IERC20 _assetToken) { assetToken = _assetToken; lendToken = new LendToken(); } /** * @dev assetToken must be approved before transfer */ function deposit(uint256 amount) public nonReentrant { require(amount > 0, "NO_ZERO_AMOUNT"); require(exceedsDepositLimit(amount) == false, "AMOUNT_EXCEEDS_LIMIT"); address sender = _msgSender(); assetToken.transferFrom(sender, address(this), amount); lendToken.mint(sender, amount); } function withdraw(uint256 amount) public nonReentrant { require(amount > 0, "NO_ZERO_AMOUNT"); address sender = _msgSender(); lendToken.burnFrom(sender, amount); assetToken.transfer(sender, amount); } function setLimitDeposit(uint256 amount) public onlyOwner { limitParticipation = amount; } function exceedsDepositLimit(uint256 amount) internal view returns (bool) { uint256 sum = amount + poolBalance(); return (amount * 100) / sum > limitParticipation; } function poolBalance() internal view returns (uint256) { return assetToken.balanceOf(address(this)); } function createLoan( uint256 amount, uint256 interest, uint8 installmentNumber, uint8 installmentAmount, address recipient ) public { require(borrowerData[recipient].exist, "BORROWER_DOESNT_EXIST"); require(canApproveLoan(installmentAmount, recipient), "CANNOT_APPROVE_LOAN"); Loan memory nxtLoan; nxtLoan.amount = amount; nxtLoan.interest = interest; nxtLoan.installmentNumber = installmentNumber; nxtLoan.installmentAmount = installmentAmount; nxtLoan.recipient = recipient; nxtLoan.startDate = block.timestamp; uint256 loanNumber = currentLoan[recipient]; loans[recipient][loanNumber] = nxtLoan; currentLoan[recipient] = loanNumber + 1; uint256 paidAmount = (amount * (interest + 100)) / 100; expectedInterest += ((paidAmount + poolBalance() - amount) * 100) / poolBalance() - 100; assetToken.transfer(recipient, amount); } function canApproveLoan(uint256 installmentAmount, address recipient) public returns (bool) { Borrower memory borrower = borrowerData[recipient]; uint256 agePts = getAgeScore(borrower.age); uint256 laboralPts = getStatusScore(borrower.status); uint256 incomePts = getIncomeScore(borrower.income - installmentAmount); uint256 walletPts = getWalletScore(borrower.walletActivity); uint256 comunityPts = getCommunityScore(borrower.comunityScore); uint256 evidenceScore = borrower.evidence ? 5 : 0; uint256 score = ((agePts + laboralPts + incomePts + walletPts + comunityPts + evidenceScore) * 100) / 55; return score >= 3 ? true : false; } function payLoan( uint256 amount, uint256 loanId, address loanRecipient ) public { Loan storage curLoan = loans[loanRecipient][loanId]; require(curLoan.amount > 0, "LOAN_ALREADY_PAID"); require(amount >= curLoan.installmentAmount, "NOT_INSTALLMENT_AMOUNT"); uint256 finalAmount = curLoan.installmentAmount > curLoan.amount ? curLoan.amount : curLoan.installmentAmount; uint256 prevAmount = curLoan.amount; assetToken.transferFrom(loanRecipient, address(this), finalAmount); unchecked { curLoan.currentInterest = ((curLoan.amount * curLoan.interest) / 100) / 12; uint256 principal = curLoan.installmentAmount - curLoan.currentInterest; curLoan.amount -= principal; } if (curLoan.amount > prevAmount) curLoan.amount = 0; lendToken.addPoolGains(curLoan.currentInterest); } function getLoan(address borrower, uint256 loanId) public view returns (Loan memory) { return loans[borrower][loanId]; } function registerBorrower( address borrowerAddress, uint256 age, LaboralStatus status, uint256 income, uint256 activity, uint256 score, bool evidence ) public onlyOwner { borrowerData[borrowerAddress] = Borrower( age, status, income, activity, score, evidence, true ); } function getAgeScore(uint256 age) internal pure returns (uint256 score) { if (age >= 18 && age <= 22) return 6; if (age >= 23 && age <= 40) return 10; if (age >= 41 && age <= 60) return 8; if (age >= 60) return 3; } function getStatusScore(LaboralStatus status) internal returns (uint256 score) { if (uint256(status) == uint256(LaboralStatus.Employed)) return 10; if (uint256(status) == uint256(LaboralStatus.SelfEmployee)) return 8; if (uint256(status) == uint256(LaboralStatus.Student)) return 3; if (uint256(status) == uint256(LaboralStatus.Unemployed)) return 0; } function getIncomeScore(uint256 delta) internal pure returns (uint256 score) { if (delta >= 0 && delta <= 50) return 10; if (delta >= 51 && delta <= 100) return 5; if (delta >= 100) return 0; } function getWalletScore(uint256 activity) internal pure returns (uint256 score) { if (activity >= 0 && activity <= 4) return 3; if (activity >= 5 && activity <= 15) return 6; if (activity >= 15 && activity <= 25) return 8; if (activity >= 25) return 10; } function getCommunityScore(uint256 comScore) internal pure returns (uint256 score) { if (comScore >= 0 && comScore <= 2) return 0; if (comScore == 3) return 3; if (comScore == 4) return 7; if (comScore == 5) return 10; } }
* @dev lendToken is 1:1 with asset token. Helps calculate and represent share of the pool/
IERC20 public assetToken;
12,676,535
[ 1, 80, 409, 1345, 353, 404, 30, 21, 598, 3310, 1147, 18, 670, 292, 1121, 4604, 471, 2406, 7433, 434, 326, 2845, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 467, 654, 39, 3462, 1071, 3310, 1345, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./DirectLoanBaseMinimal.sol"; import "../../../utils/ContractKeys.sol"; /** * @title DirectLoanFixed * @author NFTfi * @notice Main contract for NFTfi Direct Loans Fixed Type. This contract manages the ability to create NFT-backed * peer-to-peer loans of type Fixed (agreed to be a fixed-repayment loan) where the borrower pays the * maximumRepaymentAmount regardless of whether they repay early or not. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. */ contract DirectLoanFixedOffer is DirectLoanBaseMinimal { /* ********** */ /* DATA TYPES */ /* ********** */ bytes32 public constant LOAN_TYPE = bytes32("DIRECT_LOAN_FIXED_OFFER"); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` and permitted erc20-s * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _permittedErc20s - list of permitted ERC20 token contract addresses */ constructor( address _admin, address _nftfiHub, address[] memory _permittedErc20s ) DirectLoanBaseMinimal( _admin, _nftfiHub, ContractKeys.getIdFromStringKey("DIRECT_LOAN_COORDINATOR"), _permittedErc20s ) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. * @param _borrowerSettings - Some extra parameters that the borrower needs to set when accepting an offer. */ function acceptOffer( Offer memory _offer, Signature memory _signature, BorrowerSettings memory _borrowerSettings ) external whenNotPaused nonReentrant { address nftWrapper = _getWrapper(_offer.nftCollateralContract); _loanSanityChecks(_offer, nftWrapper); _loanSanityChecksOffer(_offer); _acceptOffer( LOAN_TYPE, _setupLoanTerms(_offer, nftWrapper), _setupLoanExtras(_borrowerSettings.revenueSharePartner, _borrowerSettings.referralFeeInBasisPoints), _offer, _signature ); } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view override returns (uint256) { LoanTerms storage loan = loanIdToLoan[_loanId]; return loan.maximumRepaymentAmount; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _loanType - The loan type being created. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanExtras - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoanExtras. * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. */ function _acceptOffer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, Offer memory _offer, Signature memory _signature ) internal { // Check loan nonces. These are different from Ethereum account nonces. // Here, these are uint256 numbers that should uniquely identify // each signature for each user (i.e. each user should only create one // off-chain signature for each nonce, with a nonce being any arbitrary // uint256 value that they have not used yet for an off-chain NFTfi // signature). require(!_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce], "Lender nonce invalid"); _nonceHasBeenUsedForUser[_signature.signer][_signature.nonce] = true; require(NFTfiSigningUtils.isValidLenderSignature(_offer, _signature), "Lender signature is invalid"); address bundle = hub.getContract(ContractKeys.NFTFI_BUNDLER); require(_loanTerms.nftCollateralContract != bundle, "Collateral cannot be bundle"); uint32 loanId = _createLoan(_loanType, _loanTerms, _loanExtras, msg.sender, _signature.signer, _offer.referrer); // Emit an event with all relevant details from this transaction. emit LoanStarted(loanId, msg.sender, _signature.signer, _loanTerms, _loanExtras); } /** * @dev Creates a `LoanTerms` struct using data sent as the lender's `_offer` on `acceptOffer`. * This is needed in order to avoid stack too deep issues. * Since this is a Fixed loan type loanInterestRateForDurationInBasisPoints is ignored. */ function _setupLoanTerms(Offer memory _offer, address _nftWrapper) internal view returns (LoanTerms memory) { return LoanTerms({ loanERC20Denomination: _offer.loanERC20Denomination, loanPrincipalAmount: _offer.loanPrincipalAmount, maximumRepaymentAmount: _offer.maximumRepaymentAmount, nftCollateralContract: _offer.nftCollateralContract, nftCollateralWrapper: _nftWrapper, nftCollateralId: _offer.nftCollateralId, loanStartTime: uint64(block.timestamp), loanDuration: _offer.loanDuration, loanInterestRateForDurationInBasisPoints: uint16(0), loanAdminFeeInBasisPoints: _offer.loanAdminFeeInBasisPoints, borrower: msg.sender }); } /** * @dev Calculates the payoff amount and admin fee * * @param _loanTerms - Struct containing all the loan's parameters */ function _payoffAndFee(LoanTerms memory _loanTerms) internal pure override returns (uint256 adminFee, uint256 payoffAmount) { // Calculate amounts to send to lender and admins uint256 interestDue = _loanTerms.maximumRepaymentAmount - _loanTerms.loanPrincipalAmount; adminFee = LoanChecksAndCalculations.computeAdminFee( interestDue, uint256(_loanTerms.loanAdminFeeInBasisPoints) ); payoffAmount = _loanTerms.maximumRepaymentAmount - adminFee; } /** * @dev Function that performs some validation checks over loan parameters when accepting an offer * */ function _loanSanityChecksOffer(LoanData.Offer memory _offer) internal pure { require( _offer.maximumRepaymentAmount >= _offer.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "./LoanChecksAndCalculations.sol"; import "./LoanAirdropUtils.sol"; import "../../BaseLoan.sol"; import "../../../utils/NftReceiver.sol"; import "../../../utils/NFTfiSigningUtils.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IPermittedNFTs.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title DirectLoanBase * @author NFTfi * @notice Main contract for NFTfi Direct Loans Type. This contract manages the ability to create NFT-backed * peer-to-peer loans. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. * * * If the loan was created as a ProRated type loan (pro-rata interest loan), then the user only pays the principal plus * pro-rata interest if repaid early. * However, if the loan was was created as a Fixed type loan (agreed to be a fixed-repayment loan), then the borrower * pays the maximumRepaymentAmount regardless of whether they repay early or not. * */ abstract contract DirectLoanBaseMinimal is IDirectLoanBase, IPermittedERC20s, BaseLoan, NftReceiver, LoanData { using SafeERC20 for IERC20; /* ******* */ /* STORAGE */ /* ******* */ uint16 public constant HUNDRED_PERCENT = 10000; bytes32 public immutable override LOAN_COORDINATOR; /** * @notice The maximum duration of any loan started for this loan type, measured in seconds. This is both a * sanity-check for borrowers and an upper limit on how long admins will have to support v1 of this contract if they * eventually deprecate it, as well as a check to ensure that the loan duration never exceeds the space alotted for * it in the loan struct. */ uint256 public override maximumLoanDuration = 53 weeks; /** * @notice The percentage of interest earned by lenders on this platform that is taken by the contract admin's as a * fee, measured in basis points (hundreths of a percent). The max allowed value is 10000. */ uint16 public override adminFeeInBasisPoints = 25; /** * @notice A mapping from a loan's identifier to the loan's details, represted by the loan struct. */ mapping(uint32 => LoanTerms) public override loanIdToLoan; mapping(uint32 => LoanExtras) public loanIdToLoanExtras; /** * @notice A mapping tracking whether a loan has either been repaid or liquidated. This prevents an attacker trying * to repay or liquidate the same loan twice. */ mapping(uint32 => bool) public override loanRepaidOrLiquidated; /** * @dev keeps track of tokens being held as loan collateral, so we dont allow these * to be transferred with the aridrop draining functions */ mapping(address => mapping(uint256 => uint256)) private _escrowTokens; /** * @notice A mapping that takes both a user's address and a loan nonce that was first used when signing an off-chain * order and checks whether that nonce has previously either been used for a loan, or has been pre-emptively * cancelled. The nonce referred to here is not the same as an Ethereum account's nonce. We are referring instead to * nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi orders. * * These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. Each * nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the borrower * in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would submit a * user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. */ mapping(address => mapping(uint256 => bool)) internal _nonceHasBeenUsedForUser; /** * @notice A mapping from an ERC20 currency address to whether that currency * is permitted to be used by this contract. */ mapping(address => bool) private erc20Permits; INftfiHub public immutable hub; /* ****** */ /* EVENTS */ /* ****** */ /** * @notice This event is fired whenever the admins change the percent of interest rates earned that they charge as a * fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param newAdminFee - The new admin fee measured in basis points. This is a percent of the interest paid upon a * loan's completion that go to the contract admins. */ event AdminFeeUpdated(uint16 newAdminFee); /** * @notice This event is fired whenever the admins change the maximum duration of any loan started for this loan * type. * * @param newMaximumLoanDuration - The new maximum duration. */ event MaximumLoanDurationUpdated(uint256 newMaximumLoanDuration); /** * @notice This event is fired whenever a borrower begins a loan by calling NFTfi.beginLoan(), which can only occur * after both the lender and borrower have approved their ERC721 and ERC20 contracts to use NFTfi, and when they * both have signed off-chain messages that agree on the terms of the loan. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. */ event LoanStarted( uint32 indexed loanId, address indexed borrower, address indexed lender, LoanTerms loanTerms, LoanExtras loanExtras ); /** * @notice This event is fired whenever a borrower successfully repays their loan, paying * principal-plus-interest-minus-fee to the lender in loanERC20Denomination, paying fee to owner in * loanERC20Denomination, and receiving their NFT collateral back. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param amountPaidToLender The amount of ERC20 that the borrower paid to the lender, measured in the smalled * units of loanERC20Denomination. * @param adminFee The amount of interest paid to the contract admins, measured in the smalled units of * loanERC20Denomination and determined by adminFeeInBasisPoints. This amount never exceeds the amount of interest * earned. * @param revenueShare The amount taken from admin fee amount shared with the partner. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param loanERC20Denomination - The ERC20 contract of the currency being used as principal/interest for this * loan. */ event LoanRepaid( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 amountPaidToLender, uint256 adminFee, uint256 revenueShare, address revenueSharePartner, address nftCollateralContract, address loanERC20Denomination ); /** * @notice This event is fired whenever a lender liquidates an outstanding loan that is owned to them that has * exceeded its duration. The lender receives the underlying NFT collateral, and the borrower no longer needs to * repay the loan principal-plus-interest. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanMaturityDate - The unix time (measured in seconds) that the loan became due and was eligible for * liquidation. * @param loanLiquidationDate - The unix time (measured in seconds) that liquidation occurred. * @param nftCollateralContract - The ERC721 contract of the NFT collateral */ event LoanLiquidated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 loanMaturityDate, uint256 loanLiquidationDate, address nftCollateralContract ); /** * @notice This event is fired when some of the terms of a loan are being renegotiated. * * @param loanId - The unique identifier for the loan to be renegotiated * @param newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender for the * renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, uses transfer from, * frontend will have to propmt an erc20 approve for this from the borrower to the lender * @param renegotiationAdminFee renegotiationFee admin portion based on determined by adminFeeInBasisPoints */ event LoanRenegotiated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint32 newLoanDuration, uint256 newMaximumRepaymentAmount, uint256 renegotiationFee, uint256 renegotiationAdminFee ); /** * @notice This event is fired whenever the admin sets a ERC20 permit. * * @param erc20Contract - Address of the ERC20 contract. * @param isPermitted - Signals ERC20 permit. */ event ERC20Permit(address indexed erc20Contract, bool isPermitted); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _loanCoordinatorKey - * @param _permittedErc20s - */ constructor( address _admin, address _nftfiHub, bytes32 _loanCoordinatorKey, address[] memory _permittedErc20s ) BaseLoan(_admin) { hub = INftfiHub(_nftfiHub); LOAN_COORDINATOR = _loanCoordinatorKey; for (uint256 i = 0; i < _permittedErc20s.length; i++) { _setERC20Permit(_permittedErc20s[i], true); } } /* *************** */ /* ADMIN FUNCTIONS */ /* *************** */ /** * @notice This function can be called by admins to change the maximumLoanDuration. Note that they can never change * maximumLoanDuration to be greater than UINT32_MAX, since that's the maximum space alotted for the duration in the * loan struct. * * @param _newMaximumLoanDuration - The new maximum loan duration, measured in seconds. */ function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner { require(_newMaximumLoanDuration <= uint256(type(uint32).max), "Loan duration overflow"); maximumLoanDuration = _newMaximumLoanDuration; emit MaximumLoanDurationUpdated(_newMaximumLoanDuration); } /** * @notice This function can be called by admins to change the percent of interest rates earned that they charge as * a fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This is a percent of the interest * paid upon a loan's completion that go to the contract admins. */ function updateAdminFee(uint16 _newAdminFeeInBasisPoints) external onlyOwner { require(_newAdminFeeInBasisPoints <= HUNDRED_PERCENT, "basis points > 10000"); adminFeeInBasisPoints = _newAdminFeeInBasisPoints; emit AdminFeeUpdated(_newAdminFeeInBasisPoints); } /** * @notice used by the owner account to be able to drain ERC20 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _receiver - receiver of the token */ function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner { IERC20 tokenContract = IERC20(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); require(amount > 0, "no tokens owned"); tokenContract.safeTransfer(_receiver, amount); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function setERC20Permit(address _erc20, bool _permit) external onlyOwner { _setERC20Permit(_erc20, _permit); } /** * @notice This function can be called by admins to change the permitted status of a batch of ERC20 currency. This * includes both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20s - The addresses of the ERC20 currencies whose permit list status changed. * @param _permits - The new statuses of whether the currency is permitted or not. */ function setERC20Permits(address[] memory _erc20s, bool[] memory _permits) external onlyOwner { require(_erc20s.length == _permits.length, "setERC20Permits function information arity mismatch"); for (uint256 i = 0; i < _erc20s.length; i++) { _setERC20Permit(_erc20s[i], _permits[i]); } } /** * @notice used by the owner account to be able to drain ERC721 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC721Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC721 tokenContract = IERC721(_tokenAddress); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(tokenContract.ownerOf(_tokenId) == address(this), "nft not owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId); } /** * @notice used by the owner account to be able to drain ERC1155 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC1155Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC1155 tokenContract = IERC1155(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this), _tokenId); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(amount > 0, "no nfts owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId, amount, ""); } function mintObligationReceipt(uint32 _loanId) external nonReentrant { address borrower = loanIdToLoan[_loanId].borrower; require(msg.sender == borrower, "sender has to be borrower"); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanCoordinator.mintObligationReceipt(_loanId, borrower); delete loanIdToLoan[_loanId].borrower; } /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) external whenNotPaused nonReentrant { _renegotiateLoan( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _lenderNonce, _expiry, _lenderSignature ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function payBackLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.payBackChecks(_loanId, hub); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); _payBackLoan(_loanId, borrower, lender, loan); _resolveLoan(_loanId, borrower, loan, loanCoordinator); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice This function is called by a lender once a loan has finished its duration and the borrower still has not * repaid. The lender can call this function to seize the underlying NFT collateral, although the lender gives up * all rights to the principal-plus-collateral by doing so. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause * the contract and hold hostage the NFT's that are still within it. * * We intentionally allow anybody to call this function, although only the lender will end up receiving the seized * collateral. We are exploring the possbility of incentivizing users to call this function by using some of the * admin funds. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function liquidateOverdueLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); // Ensure that the loan is indeed overdue, since we can only liquidate overdue loans. uint256 loanMaturityDate = uint256(loan.loanStartTime) + uint256(loan.loanDuration); require(block.timestamp > loanMaturityDate, "Loan is not overdue yet"); require(msg.sender == lender, "Only lender can liquidate"); _resolveLoan(_loanId, lender, loan, loanCoordinator); // Emit an event with all relevant details from this transaction. emit LoanLiquidated( _loanId, borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, loanMaturityDate, block.timestamp, loan.nftCollateralContract ); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice this function initiates a flashloan to pull an airdrop from a tartget contract * * @param _loanId - * @param _target - address of the airdropping contract * @param _data - function selector to be called on the airdropping contract * @param _nftAirdrop - address of the used claiming nft in the drop * @param _nftAirdropId - id of the used claiming nft in the drop * @param _is1155 - * @param _nftAirdropAmount - amount in case of 1155 */ function pullAirdrop( uint32 _loanId, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount ) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms memory loan = loanIdToLoan[_loanId]; LoanAirdropUtils.pullAirdrop( _loanId, loan, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, hub ); } /** * @notice this function creates a proxy contract wrapping the collateral to be able to catch an expected airdrop * * @param _loanId - */ function wrapCollateral(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms storage loan = loanIdToLoan[_loanId]; _escrowTokens[loan.nftCollateralContract][loan.nftCollateralId] -= 1; (address instance, uint256 receiverId) = LoanAirdropUtils.wrapCollateral(_loanId, loan, hub); _escrowTokens[instance][receiverId] += 1; } /** * @notice This function can be called by either a lender or a borrower to cancel all off-chain orders that they * have signed that contain this nonce. If the off-chain orders were created correctly, there should only be one * off-chain order that contains this nonce at all. * * The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi * orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. * Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the * borrower in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would * submit a user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * * @param _nonce - User nonce */ function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external { require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], "Invalid nonce"); _nonceHasBeenUsedForUser[msg.sender][_nonce] = true; } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view virtual returns (uint256); /** * @notice This function can be used to view whether a particular nonce for a particular user has already been used, * either from a successful loan or a cancelled off-chain order. * * @param _user - The address of the user. This function works for both lenders and borrowers alike. * @param _nonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain * NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain * order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or * the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * * @return A bool representing whether or not this nonce has been used for this user. */ function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view override returns (bool) { return _nonceHasBeenUsedForUser[_user][_nonce]; } /** * @notice This function can be called by anyone to get the permit associated with the erc20 contract. * * @param _erc20 - The address of the erc20 contract. * * @return Returns whether the erc20 is permitted */ function getERC20Permit(address _erc20) public view override returns (bool) { return erc20Permits[_erc20]; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. IMPORTANT: Frontend will have to propt the caller to do an ERC20 approve for * the fee amount from themselves (borrower/obligation reciept holder) to the lender (promissory note holder) * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender and * the admin for the renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, * uses transfer from, frontend will have to propmt an erc20 approve for this from the borrower to the lender, * admin fee is calculated by the loan's loanAdminFeeInBasisPoints value * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function _renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) internal { LoanTerms storage loan = loanIdToLoan[_loanId]; (address borrower, address lender) = LoanChecksAndCalculations.renegotiationChecks( loan, _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _lenderNonce, hub ); _nonceHasBeenUsedForUser[lender][_lenderNonce] = true; require( NFTfiSigningUtils.isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, Signature({signer: lender, nonce: _lenderNonce, expiry: _expiry, signature: _lenderSignature}) ), "Renegotiation signature is invalid" ); uint256 renegotiationAdminFee; /** * @notice Transfers fee to the lender immediately * @dev implements Checks-Effects-Interactions pattern by modifying state only after * the transfer happened successfully, we also add the nonReentrant modifier to * the pbulic versions */ if (_renegotiationFee > 0) { renegotiationAdminFee = LoanChecksAndCalculations.computeAdminFee( _renegotiationFee, loan.loanAdminFeeInBasisPoints ); // Transfer principal-plus-interest-minus-fees from the caller (always has to be borrower) to lender IERC20(loan.loanERC20Denomination).safeTransferFrom( borrower, lender, _renegotiationFee - renegotiationAdminFee ); // Transfer fees from the caller (always has to be borrower) to admins IERC20(loan.loanERC20Denomination).safeTransferFrom(borrower, owner(), renegotiationAdminFee); } loan.loanDuration = _newLoanDuration; loan.maximumRepaymentAmount = _newMaximumRepaymentAmount; emit LoanRenegotiated( _loanId, borrower, lender, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, renegotiationAdminFee ); } /** * @dev Transfer collateral NFT from borrower to this contract and principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoan( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32) { // Transfer collateral from borrower to this contract to be held until // loan completion. _transferNFT(_loanTerms, _borrower, address(this)); return _createLoanNoNftTransfer(_loanType, _loanTerms, _loanExtras, _borrower, _lender, _referrer); } /** * @dev Transfer principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoanNoNftTransfer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32 loanId) { _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] += 1; uint256 referralfee = LoanChecksAndCalculations.computeReferralFee( _loanTerms.loanPrincipalAmount, _loanExtras.referralFeeInBasisPoints, _referrer ); uint256 principalAmount = _loanTerms.loanPrincipalAmount - referralfee; if (referralfee > 0) { // Transfer the referral fee from lender to referrer. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _referrer, referralfee); } // Transfer principal from lender to borrower. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _borrower, principalAmount); // Issue an ERC721 promissory note to the lender that gives them the // right to either the principal-plus-interest or the collateral, // and an obligation note to the borrower that gives them the // right to pay back the loan and get the collateral back. IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanId = loanCoordinator.registerLoan(_lender, _loanType); // Add the loan to storage before moving collateral/principal to follow // the Checks-Effects-Interactions pattern. loanIdToLoan[loanId] = _loanTerms; loanIdToLoanExtras[loanId] = _loanExtras; return loanId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loanTerms - Struct containing all the loan's parameters * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanTerms memory _loanTerms, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loanTerms.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loanTerms.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loanTerms.nftCollateralContract, _loanTerms.nftCollateralId ), "NFT not successfully transferred" ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function _payBackLoan( uint32 _loanId, address _borrower, address _lender, LoanTerms memory _loan ) internal { // Fetch loan details from storage, but store them in memory for the sake of saving gas. LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId]; (uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan); // Transfer principal-plus-interest-minus-fees from the caller to lender IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount); uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare( adminFee, loanExtras.revenueShareInBasisPoints ); // PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare // > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the // adminFee is low if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) { adminFee -= revenueShare; // Transfer revenue share from the caller to permitted partner IERC20(_loan.loanERC20Denomination).safeTransferFrom( msg.sender, loanExtras.revenueSharePartner, revenueShare ); } // Transfer fees from the caller to admins IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, owner(), adminFee); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, _borrower, _lender, _loan.loanPrincipalAmount, _loan.nftCollateralId, payoffAmount, adminFee, revenueShare, loanExtras.revenueSharePartner, // this could be a non address zero even if revenueShare is 0 _loan.nftCollateralContract, _loan.loanERC20Denomination ); } /** * @notice A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when * `liquidateOverdueLoan`. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoan( uint32 _loanId, address _nftReceiver, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { _resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator); // Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue // loan _transferNFT(_loanTerms, address(this), _nftReceiver); } /** * @notice Resolving the loan without trasferring the nft to provide a base for the bundle * break up of the bundled loans * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoanNoNftTransfer( uint32 _loanId, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { // Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design // pattern loanRepaidOrLiquidated[_loanId] = true; _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1; // Destroy the lender's promissory note for this loan and borrower obligation receipt _loanCoordinator.resolveLoan(_loanId); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function _setERC20Permit(address _erc20, bool _permit) internal { require(_erc20 != address(0), "erc20 is zero address"); erc20Permits[_erc20] = _permit; emit ERC20Permit(_erc20, _permit); } /** * @dev Performs some validation checks over loan parameters * */ function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view { require(getERC20Permit(_offer.loanERC20Denomination), "Currency denomination is not permitted"); require(_nftWrapper != address(0), "NFT collateral contract is not permitted"); require(uint256(_offer.loanDuration) <= maximumLoanDuration, "Loan duration exceeds maximum loan duration"); require(uint256(_offer.loanDuration) != 0, "Loan duration cannot be zero"); require( _offer.loanAdminFeeInBasisPoints == adminFeeInBasisPoints, "The admin fee has changed since this order was signed." ); } /** * @dev reads some variable values of a loan for payback functions, created to reduce code repetition */ function _getPartiesAndData(uint32 _loanId) internal view returns ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) { loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; // Fetch loan details from storage, but store them in memory for the sake of saving gas. loan = loanIdToLoan[_loanId]; if (loan.borrower != address(0)) { borrower = loan.borrower; } else { // Fetch current owner of loan obligation note. borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); } /** * @dev Creates a `LoanExtras` struct using data sent as the borrower's extra settings. * This is needed in order to avoid stack too deep issues. */ function _setupLoanExtras(address _revenueSharePartner, uint16 _referralFeeInBasisPoints) internal view returns (LoanExtras memory) { // Save loan details to a struct in memory first, to save on gas if any // of the below checks fail, and to avoid the "Stack Too Deep" error by // clumping the parameters together into one struct held in memory. return LoanExtras({ revenueSharePartner: _revenueSharePartner, revenueShareInBasisPoints: LoanChecksAndCalculations.getRevenueSharePercent(_revenueSharePartner, hub), referralFeeInBasisPoints: _referralFeeInBasisPoints }); } /** * @dev Calculates the payoff amount and admin fee */ function _payoffAndFee(LoanTerms memory _loanTerms) internal view virtual returns (uint256, uint256); /** * @dev Checks that the collateral is a supported contracts and returns what wrapper to use for the loan's NFT * collateral contract. * * @param _nftCollateralContract - The address of the the NFT collateral contract. * * @return Address of the NftWrapper to use for the loan's NFT collateral. */ function _getWrapper(address _nftCollateralContract) internal view returns (address) { return IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)).getNFTWrapper(_nftCollateralContract); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // SPDX-License-Identifier: BUSL-1.1 import "./LoanData.sol"; pragma solidity 0.8.4; interface IDirectLoanBase { function maximumLoanDuration() external view returns (uint256); function adminFeeInBasisPoints() external view returns (uint16); // solhint-disable-next-line func-name-mixedcase function LOAN_COORDINATOR() external view returns (bytes32); function loanIdToLoan(uint32) external view returns ( uint256, uint256, uint256, address, uint32, uint16, uint16, address, uint64, address, address ); function loanRepaidOrLiquidated(uint32) external view returns (bool); function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title LoanData * @author NFTfi * @notice An interface containg the main Loan struct shared by Direct Loans types. */ interface LoanData { /* ********** */ /* DATA TYPES */ /* ********** */ /** * @notice The main Loan Terms struct. This data is saved upon loan creation. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the the NFT collateral contract. * @param nftCollateralWrapper - The NFTfi wrapper of the NFT collateral contract. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanStartTime - The block.timestamp when the loan first began (measured in seconds). * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanInterestRateForDurationInBasisPoints - This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param borrower */ struct LoanTerms { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address loanERC20Denomination; uint32 loanDuration; uint16 loanInterestRateForDurationInBasisPoints; uint16 loanAdminFeeInBasisPoints; address nftCollateralWrapper; uint64 loanStartTime; address nftCollateralContract; address borrower; } /** * @notice Some extra Loan's settings struct. This data is saved upon loan creation. * We need this to avoid stack too deep errors. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a t * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.he partner, at the moment * the loan is begun. */ struct LoanExtras { address revenueSharePartner; uint16 revenueShareInBasisPoints; uint16 referralFeeInBasisPoints; } /** * @notice The offer made by the lender. Used as parameter on both acceptOffer (initiated by the borrower) and * acceptListing (initiated by the lender). * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always * have to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. */ struct Offer { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 loanDuration; uint16 loanAdminFeeInBasisPoints; address loanERC20Denomination; address referrer; } /** * @notice Signature related params. Used as parameter on both acceptOffer (containing borrower signature) and * acceptListing (containing lender signature). * * @param signer - The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * @param nonce - The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param expiry - Date when the signature expires * @param signature - The ECDSA signature of the borrower or the lender, obtained off-chain ahead of time, signing * the following combination of parameters: * - Borrower * - ListingTerms.loanERC20Denomination, * - ListingTerms.minLoanPrincipalAmount, * - ListingTerms.maxLoanPrincipalAmount, * - ListingTerms.nftCollateralContract, * - ListingTerms.nftCollateralId, * - ListingTerms.revenueSharePartner, * - ListingTerms.minLoanDuration, * - ListingTerms.maxLoanDuration, * - ListingTerms.maxInterestRateForDurationInBasisPoints, * - ListingTerms.referralFeeInBasisPoints, * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId * - Lender: * - Offer.loanERC20Denomination * - Offer.loanPrincipalAmount * - Offer.maximumRepaymentAmount * - Offer.nftCollateralContract * - Offer.nftCollateralId * - Offer.referrer * - Offer.loanDuration * - Offer.loanAdminFeeInBasisPoints * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId */ struct Signature { uint256 nonce; uint256 expiry; address signer; bytes signature; } /** * @notice Some extra parameters that the borrower needs to set when accepting an offer. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct BorrowerSettings { address revenueSharePartner; uint16 referralFeeInBasisPoints; } /** * @notice Terms the borrower set off-chain and is willing to accept automatically when fulfiled by a lender's * offer. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param minLoanPrincipalAmount - The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maxLoanPrincipalAmount - The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param minLoanDuration - The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxLoanDuration - The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxInterestRateForDurationInBasisPoints - This is maximum the interest rate (measured in basis points, * e.g. hundreths of a percent) for the loan. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct ListingTerms { uint256 minLoanPrincipalAmount; uint256 maxLoanPrincipalAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 minLoanDuration; uint32 maxLoanDuration; uint16 maxInterestRateForDurationInBasisPoints; uint16 referralFeeInBasisPoints; address revenueSharePartner; address loanERC20Denomination; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title LoanChecksAndCalculations * @author NFTfi * @notice Helper library for LoanBase */ library LoanChecksAndCalculations { uint16 private constant HUNDRED_PERCENT = 10000; /** * @dev Function that performs some validation checks before trying to repay a loan * * @param _loanId - The id of the loan being repaid */ function payBackChecks(uint32 _loanId, INftfiHub _hub) external view { checkLoanIdValidity(_loanId, _hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); // Fetch loan details from storage, but store them in memory for the sake of saving gas. (, , , , uint32 loanDuration, , , , uint64 loanStartTime, , ) = IDirectLoanBase(address(this)).loanIdToLoan( _loanId ); // When a loan exceeds the loan term, it is expired. At this stage the Lender can call Liquidate Loan to resolve // the loan. require(block.timestamp <= (uint256(loanStartTime) + uint256(loanDuration)), "Loan is expired"); } function checkLoanIdValidity(uint32 _loanId, INftfiHub _hub) public view { require( IDirectLoanCoordinator(_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())).isValidLoanId( _loanId, address(this) ), "invalid loanId" ); } /** * @dev Function that the partner is permitted and returns its shared percent. * * @param _revenueSharePartner - Partner's address * * @return The revenue share percent for the partner. */ function getRevenueSharePercent(address _revenueSharePartner, INftfiHub _hub) external view returns (uint16) { // return soon if no partner is set to avoid a public call if (_revenueSharePartner == address(0)) { return 0; } uint16 revenueSharePercent = IPermittedPartners(_hub.getContract(ContractKeys.PERMITTED_PARTNERS)) .getPartnerPermit(_revenueSharePartner); return revenueSharePercent; } /** * @dev Performs some validation checks before trying to renegotiate a loan. * Needed to avoid stack too deep. * * @param _loan - The main Loan Terms struct. * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @return Borrower and Lender addresses */ function renegotiationChecks( LoanData.LoanTerms memory _loan, uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _lenderNonce, INftfiHub _hub ) external view returns (address, address) { checkLoanIdValidity(_loanId, _hub); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); uint256 smartNftId = loanCoordinator.getLoanData(_loanId).smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can initiate"); require(block.timestamp <= (uint256(_loan.loanStartTime) + _newLoanDuration), "New duration already expired"); require( uint256(_newLoanDuration) <= IDirectLoanBase(address(this)).maximumLoanDuration(), "New duration exceeds maximum loan duration" ); require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); require( _newMaximumRepaymentAmount >= _loan.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); // Fetch current owner of loan promissory note. address lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); require( !IDirectLoanBase(address(this)).getWhetherNonceHasBeenUsedForUser(lender, _lenderNonce), "Lender nonce invalid" ); return (borrower, lender); } /** * @dev Performs some validation checks over loan parameters when accepting a listing * */ function bindingTermsSanityChecks(LoanData.ListingTerms memory _listingTerms, LoanData.Offer memory _offer) external pure { // offer vs listing validations require(_offer.loanERC20Denomination == _listingTerms.loanERC20Denomination, "Invalid loanERC20Denomination"); require( _offer.loanPrincipalAmount >= _listingTerms.minLoanPrincipalAmount && _offer.loanPrincipalAmount <= _listingTerms.maxLoanPrincipalAmount, "Invalid loanPrincipalAmount" ); uint256 maxRepaymentLimit = _offer.loanPrincipalAmount + (_offer.loanPrincipalAmount * _listingTerms.maxInterestRateForDurationInBasisPoints) / HUNDRED_PERCENT; require(_offer.maximumRepaymentAmount <= maxRepaymentLimit, "maxInterestRateForDurationInBasisPoints violated"); require( _offer.loanDuration >= _listingTerms.minLoanDuration && _offer.loanDuration <= _listingTerms.maxLoanDuration, "Invalid loanDuration" ); } /** * @notice A convenience function computing the revenue share taken from the admin fee to transferr to the permitted * partner. * * @param _adminFee - The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due * as an admin fee. * @param _revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a the partner, at the moment the loan is begun. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the `revenueSharePartner`. */ function computeRevenueShare(uint256 _adminFee, uint256 _revenueShareInBasisPoints) external pure returns (uint256) { return (_adminFee * _revenueShareInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the adminFee taken from a specified quantity of interest. * * @param _interestDue - The amount of interest due, measured in the smallest quantity of the ERC20 currency being * used to pay the interest. * @param _adminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be taken * as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due as an admin * fee. */ function computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) external pure returns (uint256) { return (_interestDue * _adminFeeInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the referral fee taken from the loan principal amount to transferr to * the referrer. * * @param _loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param _referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the referrer. */ function computeReferralFee( uint256 _loanPrincipalAmount, uint256 _referralFeeInBasisPoints, address _referrer ) external pure returns (uint256) { if (_referralFeeInBasisPoints == 0 || _referrer == address(0)) { return 0; } return (_loanPrincipalAmount * _referralFeeInBasisPoints) / HUNDRED_PERCENT; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IAirdropFlashLoan.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../airdrop/IAirdropReceiverFactory.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title LoanAirdropUtils * @author NFTfi * @notice Helper library for LoanBase */ library LoanAirdropUtils { /** * @notice This event is fired whenever a flashloan is initiated to pull an airdrop * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param target - address of the airdropping contract * @param data - function selector to be called */ event AirdropPulledFlashloan( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, address target, bytes data ); /** * @notice This event is fired whenever the collateral gets wrapped in an airdrop receiver * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The contract of the NFT collateral * @param receiverId - id of the created AirdropReceiver, takes the place of nftCollateralId on the loan * @param receiverInstance - address of the created AirdropReceiver */ event CollateralWrapped( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, uint256 receiverId, address receiverInstance ); function pullAirdrop( uint32 _loanId, LoanData.LoanTerms memory _loan, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, INftfiHub _hub ) external { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); address borrower; // scoped to aviod stack too deep { IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } } require(msg.sender == borrower, "Only borrower can airdrop"); { IAirdropFlashLoan airdropFlashLoan = IAirdropFlashLoan(_hub.getContract(ContractKeys.AIRDROP_FLASH_LOAN)); _transferNFT(_loan, address(this), address(airdropFlashLoan)); airdropFlashLoan.pullAirdrop( _loan.nftCollateralContract, _loan.nftCollateralId, _loan.nftCollateralWrapper, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, borrower ); } // revert if the collateral hasn't been transferred back before it ends require( INftWrapper(_loan.nftCollateralWrapper).isOwner( address(this), _loan.nftCollateralContract, _loan.nftCollateralId ), "Collateral should be returned" ); emit AirdropPulledFlashloan( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, _target, _data ); } function wrapCollateral( uint32 _loanId, LoanData.LoanTerms storage _loan, INftfiHub _hub ) external returns (address instance, uint256 receiverId) { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); // Fetch the current lender of the promissory note corresponding to this overdue loan. IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can wrapp"); IAirdropReceiverFactory factory = IAirdropReceiverFactory(_hub.getContract(ContractKeys.AIRDROP_FACTORY)); (instance, receiverId) = factory.createAirdropReceiver(address(this)); // transfer collateral to airdrop receiver wrapper _transferNFTtoAirdropReceiver(_loan, instance, borrower); emit CollateralWrapped( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, receiverId, instance ); // set the receiver as the new collateral _loan.nftCollateralContract = instance; _loan.nftCollateralId = receiverId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loan - * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanData.LoanTerms memory _loan, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loan.nftCollateralContract, _loan.nftCollateralId ), "NFT not successfully transferred" ); } /** * @dev Transfers several types of NFTs to an airdrop receiver with an airdrop beneficiary * address attached as supplementing data using a wrapper that knows how to handle each case. * * @param _loan - * @param _airdropReceiverInstance - Recipient of the transfer * @param _airdropBeneficiary - Beneficiary of the future airdops */ function _transferNFTtoAirdropReceiver( LoanData.LoanTerms memory _loan, address _airdropReceiverInstance, address _airdropBeneficiary ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).wrapAirdropReceiver.selector, _airdropReceiverInstance, _loan.nftCollateralContract, _loan.nftCollateralId, _airdropBeneficiary ), "NFT was not successfully migrated" ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../utils/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title BaseLoan * @author NFTfi * @dev Implements base functionalities common to all Loan types. * Mostly related to governance and security. */ abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard { /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @notice Sets the admin of the contract. * * @param _admin - Initial admin of this contract. */ constructor(address _admin) Ownable(_admin) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev Triggers stopped state. * * Requirements: * * - Only the owner can call this method. * - The contract must not be paused. */ function pause() external onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - Only the owner can call this method. * - The contract must be paused. */ function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; /** * @title NftReceiver * @author NFTfi * @dev Base contract with capabilities for receiving ERC1155 and ERC721 tokens */ abstract contract NftReceiver is IERC1155Receiver, ERC721Holder { /** * @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. * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if allowed */ function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @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. * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if allowed */ function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external virtual override returns (bytes4) { revert("ERC1155 batch not supported"); } /** * @dev Checks whether this contract implements the interface defined by `interfaceId`. * @param _interfaceId Id of the interface * @return true if this contract implements the interface */ function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return _interfaceId == type(IERC1155Receiver).interfaceId || _interfaceId == type(IERC721Receiver).interfaceId || _interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../interfaces/IBundleBuilder.sol"; import "../loans/direct/loanTypes/LoanData.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; /** * @title NFTfiSigningUtils * @author NFTfi * @notice Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders. * Based on the version of this same contract used on NFTfi V1 */ library NFTfiSigningUtils { /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev This function gets the current chain ID. */ function getChainID() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature) external view returns (bool) { return isValidBorrowerSignature(_listingTerms, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignature( LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature) external view returns (bool) { return isValidLenderSignature(_offer, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignature( LoanData.Offer memory _offer, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID()) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedOffer(_offer), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided * off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * - expiry - The date when the renegotiation offer expires * - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _lenderNonce * - _expiry * - address of this contract * - chainId */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _signature, address(this) ); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) { return abi.encodePacked( _offer.loanERC20Denomination, _offer.loanPrincipalAmount, _offer.maximumRepaymentAmount, _offer.nftCollateralContract, _offer.nftCollateralId, _offer.referrer, _offer.loanDuration, _offer.loanAdminFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) { return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IDirectLoanCoordinator * @author NFTfi * @dev DirectLoanCoordinator interface. */ interface IDirectLoanCoordinator { enum StatusType { NOT_EXISTS, NEW, RESOLVED } /** * @notice This struct contains data related to a loan * * @param smartNftId - The id of both the promissory note and obligation receipt. * @param status - The status in which the loan currently is. * @param loanContract - Address of the LoanType contract that created the loan. */ struct Loan { address loanContract; uint64 smartNftId; StatusType status; } function registerLoan(address _lender, bytes32 _loanType) external returns (uint32); function mintObligationReceipt(uint32 _loanId, address _borrower) external; function resolveLoan(uint32 _loanId) external; function promissoryNoteToken() external view returns (address); function obligationReceiptToken() external view returns (address); function getLoanData(uint32 _loanId) external view returns (Loan memory); function isValidLoanId(uint32 _loanId, address _loanContract) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftTypeRegistry * @author NFTfi * @dev Interface for NFT Wrappers. */ interface INftWrapper { function transferNFT( address from, address to, address nftContract, uint256 tokenId ) external returns (bool); function isOwner( address owner, address nftContract, uint256 tokenId ) external view returns (bool); function wrapAirdropReceiver( address _recipient, address _nftContract, uint256 _nftId, address _beneficiary ) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedPartners { function getPartnerPermit(address _partner) external view returns (uint16); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedERC20s { function getERC20Permit(address _erc20) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // 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 (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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IAirdropFlashLoan { function pullAirdrop( address _nftCollateralContract, uint256 _nftCollateralId, address _nftWrapper, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, address _beneficiary ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IAirdropReceiver * @author NFTfi * @dev */ interface IAirdropReceiverFactory { function createAirdropReceiver(address _to) external returns (address, uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/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. * * Modified version from openzeppelin/contracts/access/Ownable.sol that allows to * initialize the owner using a parameter in the constructor */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /** * @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); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Sets the owner. */ function _setOwner(address _newOwner) private { address oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(oldOwner, _newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @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. * * NOTE: 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. * * NOTE: 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // 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: BUSL-1.1 pragma solidity 0.8.4; interface IBundleBuilder { /** * @notice data of a erc721 bundle element * * @param tokenContract - address of the token contract * @param id - id of the token * @param safeTransferable - wether the implementing token contract has a safeTransfer function or not */ struct BundleElementERC721 { address tokenContract; uint256 id; bool safeTransferable; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param amount - amount of the token */ struct BundleElementERC20 { address tokenContract; uint256 amount; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param ids - list of ids of the tokens * @param amounts - list amounts of the tokens */ struct BundleElementERC1155 { address tokenContract; uint256[] ids; uint256[] amounts; } /** * @notice the lists of erc721-20-1155 tokens that are to be bundled * * @param erc721s list of erc721 tokens * @param erc20s list of erc20 tokens * @param erc1155s list of erc1155 tokens */ struct BundleElements { BundleElementERC721[] erc721s; BundleElementERC20[] erc20s; BundleElementERC1155[] erc1155s; } /** * @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external returns (uint256); /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // 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); } }
*********** */ CONSTRUCTOR */ *********** */* @notice Sets the admin of the contract. @param _admin - Initial admin of this contract./ solhint-disable-previous-line no-empty-blocks
constructor(address _admin) Ownable(_admin) { }
1,474,564
[ 1, 19, 3492, 13915, 916, 342, 225, 342, 225, 11511, 326, 3981, 434, 326, 6835, 18, 225, 389, 3666, 300, 10188, 3981, 434, 333, 6835, 18, 19, 3704, 11317, 17, 8394, 17, 11515, 17, 1369, 1158, 17, 5531, 17, 7996, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 2867, 389, 3666, 13, 14223, 6914, 24899, 3666, 13, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @title Queue * @author Erick Dagenais (https://github.com/edag94) * @dev Implementation of the queue data structure, providing a library with struct definition for queue storage in consuming contracts. */ library Queue { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Queue 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. // Based off the pattern used in https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol[EnumerableSet.sol] by OpenZeppelin struct QueueStorage { mapping (uint256 => bytes32) _data; uint256 _first; uint256 _last; } modifier isNotEmpty(QueueStorage storage queue) { require(!_isEmpty(queue), "Queue is empty."); _; } /** * @dev Sets the queue's initial state, with a queue size of 0. * @param queue QueueStorage struct from contract. */ function _initialize(QueueStorage storage queue) private { queue._first = 1; queue._last = 0; } /** * @dev Gets the number of elements in the queue. O(1) * @param queue QueueStorage struct from contract. */ function _length(QueueStorage storage queue) private view returns (uint256) { if (queue._last < queue._first) { return 0; } return queue._last - queue._first + 1; } /** * @dev Returns if queue is empty. O(1) * @param queue QueueStorage struct from contract. */ function _isEmpty(QueueStorage storage queue) private view returns (bool) { return _length(queue) == 0; } /** * @dev Adds an element to the back of the queue. O(1) * @param queue QueueStorage struct from contract. * @param data The added element's data. */ function _enqueue(QueueStorage storage queue, bytes32 data) private { queue._data[++queue._last] = data; } /** * @dev Removes an element from the front of the queue and returns it. O(1) * @param queue QueueStorage struct from contract. */ function _dequeue(QueueStorage storage queue) private isNotEmpty(queue) returns (bytes32 data) { data = queue._data[queue._first]; delete queue._data[queue._first++]; } /** * @dev Returns the data from the front of the queue, without removing it. O(1) * @param queue QueueStorage struct from contract. */ function _peek(QueueStorage storage queue) private view isNotEmpty(queue) returns (bytes32 data) { return queue._data[queue._first]; } /** * @dev Returns the data from the back of the queue. O(1) * @param queue QueueStorage struct from contract. */ function _peekLast(QueueStorage storage queue) private view isNotEmpty(queue) returns (bytes32 data) { return queue._data[queue._last]; } // Bytes32Queue struct Bytes32Queue { QueueStorage _inner; } /** * @dev Sets the queue's initial state, with a queue size of 0. * @param queue Bytes32Queue struct from contract. */ function initialize(Bytes32Queue storage queue) internal { _initialize(queue._inner); } /** * @dev Gets the number of elements in the queue. O(1) * @param queue Bytes32Queue struct from contract. */ function length(Bytes32Queue storage queue) internal view returns (uint256) { return _length(queue._inner); } /** * @dev Returns if queue is empty. O(1) * @param queue Bytes32Queue struct from contract. */ function isEmpty(Bytes32Queue storage queue) internal view returns (bool) { return _isEmpty(queue._inner); } /** * @dev Adds an element to the back of the queue. O(1) * @param queue Bytes32Queue struct from contract. * @param data The added element's data. */ function enqueue(Bytes32Queue storage queue, bytes32 data) internal { _enqueue(queue._inner, data); } /** * @dev Removes an element from the front of the queue and returns it. O(1) * @param queue Bytes32Queue struct from contract. */ function dequeue(Bytes32Queue storage queue) internal returns (bytes32 data) { return _dequeue(queue._inner); } /** * @dev Returns the data from the front of the queue, without removing it. O(1) * @param queue Bytes32Queue struct from contract. */ function peek(Bytes32Queue storage queue) internal view returns (bytes32 data) { return _peek(queue._inner); } /** * @dev Returns the data from the back of the queue. O(1) * @param queue Bytes32Queue struct from contract. */ function peekLast(Bytes32Queue storage queue) internal view returns (bytes32 data) { return _peekLast(queue._inner); } // AddressQueue struct AddressQueue { QueueStorage _inner; } /** * @dev Sets the queue's initial state, with a queue size of 0. * @param queue AddressQueue struct from contract. */ function initialize(AddressQueue storage queue) internal { _initialize(queue._inner); } /** * @dev Gets the number of elements in the queue. O(1) * @param queue AddressQueue struct from contract. */ function length(AddressQueue storage queue) internal view returns (uint256) { return _length(queue._inner); } /** * @dev Returns if queue is empty. O(1) * @param queue AddressQueue struct from contract. */ function isEmpty(AddressQueue storage queue) internal view returns (bool) { return _isEmpty(queue._inner); } /** * @dev Adds an element to the back of the queue. O(1) * @param queue AddressQueue struct from contract. * @param data The added element's data. */ function enqueue(AddressQueue storage queue, address data) internal { _enqueue(queue._inner, bytes32(uint256(uint160(data)))); } /** * @dev Removes an element from the front of the queue and returns it. O(1) * @param queue AddressQueue struct from contract. */ function dequeue(AddressQueue storage queue) internal returns (address data) { return address(uint160(uint256(_dequeue(queue._inner)))); } /** * @dev Returns the data from the front of the queue, without removing it. O(1) * @param queue AddressQueue struct from contract. */ function peek(AddressQueue storage queue) internal view returns (address data) { return address(uint160(uint256(_peek(queue._inner)))); } /** * @dev Returns the data from the back of the queue. O(1) * @param queue AddressQueue struct from contract. */ function peekLast(AddressQueue storage queue) internal view returns (address data) { return address(uint160(uint256(_peekLast(queue._inner)))); } // Uint256Queue struct Uint256Queue { QueueStorage _inner; } /** * @dev Sets the queue's initial state, with a queue size of 0. * @param queue Uint256Queue struct from contract. */ function initialize(Uint256Queue storage queue) internal { _initialize(queue._inner); } /** * @dev Gets the number of elements in the queue. O(1) * @param queue Uint256Queue struct from contract. */ function length(Uint256Queue storage queue) internal view returns (uint256) { return _length(queue._inner); } /** * @dev Returns if queue is empty. O(1) * @param queue Uint256Queue struct from contract. */ function isEmpty(Uint256Queue storage queue) internal view returns (bool) { return _isEmpty(queue._inner); } /** * @dev Adds an element to the back of the queue. O(1) * @param queue Uint256Queue struct from contract. * @param data The added element's data. */ function enqueue(Uint256Queue storage queue, uint256 data) internal { _enqueue(queue._inner, bytes32(data)); } /** * @dev Removes an element from the front of the queue and returns it. O(1) * @param queue Uint256Queue struct from contract. */ function dequeue(Uint256Queue storage queue) internal returns (uint256 data) { return uint256(_dequeue(queue._inner)); } /** * @dev Returns the data from the front of the queue, without removing it. O(1) * @param queue Uint256Queue struct from contract. */ function peek(Uint256Queue storage queue) internal view returns (uint256 data) { return uint256(_peek(queue._inner)); } /** * @dev Returns the data from the back of the queue. O(1) * @param queue Uint256Queue struct from contract. */ function peekLast(Uint256Queue storage queue) internal view returns (uint256 data) { return uint256(_peekLast(queue._inner)); } }
* @dev Returns the data from the front of the queue, without removing it. O(1) @param queue AddressQueue struct from contract./
function peek(AddressQueue storage queue) internal view returns (address data) { return address(uint160(uint256(_peek(queue._inner)))); }
5,372,109
[ 1, 1356, 326, 501, 628, 326, 6641, 434, 326, 2389, 16, 2887, 9427, 518, 18, 531, 12, 21, 13, 225, 2389, 5267, 3183, 1958, 628, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8032, 12, 1887, 3183, 2502, 2389, 13, 2713, 1476, 1135, 261, 2867, 501, 13, 288, 203, 3639, 327, 1758, 12, 11890, 16874, 12, 11890, 5034, 24899, 347, 3839, 12, 4000, 6315, 7872, 3719, 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 ]
./full_match/4/0xef6B80d55a50538dEF6a47b4bFc7518aD8BbB9c0/sources/Contract.sol
event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens);
contract ERC20Basic is ERC20,Owned { using SafeMath for uint256; string public constant name = "ETHTEST"; string public constant symbol = "Coin"; uint8 public constant decimals = 4; uint256 totalSupply_ = 100000 *10**uint256(decimals); uint256 transactionFee = 12; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; constructor() public { balances[msg.sender] = totalSupply_; } function tokenBuAndSellWithTaxMethod() public payable { emit TokenBuAndSellWithTax(msg.sender,msg.value,address(this).balance); } function totalSupply() public override view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public override view returns (uint256) { return balances[tokenOwner]; } function transfer(address receiver, uint256 numTokens) public override returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } function approve(address delegate, uint256 numTokens) public override returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public override view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint256 numTokens) public override returns (bool) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true; } function getbalance() public view returns(uint){ return address(this).balance; } }
769,336
[ 1, 2575, 1716, 685, 1125, 12, 2867, 8808, 1147, 5541, 16, 1758, 8808, 17571, 264, 16, 2254, 2430, 1769, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 2430, 1769, 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, 16351, 4232, 39, 3462, 8252, 353, 4232, 39, 3462, 16, 5460, 329, 225, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 533, 1071, 5381, 508, 273, 315, 1584, 44, 16961, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 27055, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 1059, 31, 203, 377, 2254, 5034, 2078, 3088, 1283, 67, 273, 25259, 380, 2163, 636, 11890, 5034, 12, 31734, 1769, 7010, 377, 2254, 5034, 2492, 14667, 273, 2593, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 377, 203, 282, 3885, 1435, 1071, 288, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 67, 31, 203, 565, 289, 203, 377, 203, 3639, 445, 225, 1147, 38, 89, 1876, 55, 1165, 1190, 7731, 1305, 1435, 1071, 8843, 429, 288, 203, 5411, 3626, 3155, 38, 89, 1876, 55, 1165, 1190, 7731, 12, 3576, 18, 15330, 16, 3576, 18, 1132, 16, 2867, 12, 2211, 2934, 12296, 1769, 203, 3639, 289, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2078, 3088, 1283, 67, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 5971, 16, 2 ]
./partial_match/1/0x793BC65f303b5c99c6fF72Ab70A4bb6d0F3dd688/sources/XetherToken.sol
* @dev function to show tokens/ether ratio @param _tokens tokens amount/ (2 * a1 - delta * (n - 1)) / 2 * n
function showTokensToEth(uint256 _tokens) public view returns (uint256 _eth, uint256 _newTokenPrice) { _eth = SafeMath.sub(actualTokenPrice.mul(2), tokenPriceIncremental.mul(_tokens.sub(1e18)).div(decimalShift)).div(2).mul(_tokens).div(decimalShift); _newTokenPrice = actualTokenPrice.sub(SafeMath.mul(_tokens.div(1e18), tokenPriceIncremental)); }
16,038,924
[ 1, 915, 358, 2405, 2430, 19, 2437, 7169, 225, 389, 7860, 2430, 3844, 19, 261, 22, 225, 279, 21, 300, 3622, 225, 261, 82, 300, 404, 3719, 342, 576, 225, 290, 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, 445, 2405, 5157, 774, 41, 451, 12, 11890, 5034, 389, 7860, 13, 1071, 1476, 1135, 261, 11890, 5034, 389, 546, 16, 2254, 5034, 389, 2704, 1345, 5147, 13, 288, 203, 282, 389, 546, 273, 14060, 10477, 18, 1717, 12, 18672, 1345, 5147, 18, 16411, 12, 22, 3631, 1147, 5147, 10798, 287, 18, 16411, 24899, 7860, 18, 1717, 12, 21, 73, 2643, 13, 2934, 2892, 12, 12586, 10544, 13, 2934, 2892, 12, 22, 2934, 16411, 24899, 7860, 2934, 2892, 12, 12586, 10544, 1769, 203, 282, 389, 2704, 1345, 5147, 273, 3214, 1345, 5147, 18, 1717, 12, 9890, 10477, 18, 16411, 24899, 7860, 18, 2892, 12, 21, 73, 2643, 3631, 1147, 5147, 10798, 287, 10019, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; interface IRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); 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 removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts); } interface IMasterChef { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint _pid, address _user) external view returns(uint amount, uint rewardDebt); } interface IDaoL1Vault is IERC20Upgradeable { function deposit(uint amount) external; function withdraw(uint share) external returns (uint); function getAllPoolInUSD() external view returns (uint); function getAllPoolInETH() external view returns (uint); } interface IChainlink { function latestAnswer() external view returns (int256); } contract TAStrategy is Initializable { using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable constant WETH = IERC20Upgradeable(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20Upgradeable constant WBTC = IERC20Upgradeable(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20Upgradeable constant USDC = IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20Upgradeable constant WBTCETH = IERC20Upgradeable(0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58); IERC20Upgradeable constant USDCETH = IERC20Upgradeable(0x397FF1542f962076d0BFE58eA045FfA2d347ACa0); IDaoL1Vault public WBTCETHVault; IDaoL1Vault public USDCETHVault; IRouter constant router = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushi IMasterChef constant masterChef = IMasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd); address public vault; uint public watermark; // In USD (18 decimals) uint public profitFeePerc; bool public mode; // Attack: true, Defence: false event InvestWBTCETH(uint WETHAmt, uint WBTCETHAmt); event InvestUSDCETH(uint WETHAmt, uint USDCETHAmt); event WithdrawWBTCETH(uint lpTokenAmt, uint WETHAmt); event WithdrawUSDCETH(uint lpTokenAmt, uint WETHAmt); event SwitchMode(uint lpTokenAmtFrom, uint lpTokenAmtTo, bool modeFrom, bool modeTo); event CollectProfitAndUpdateWatermark(uint currentWatermark, uint lastWatermark, uint fee); event AdjustWatermark(uint currentWatermark, uint lastWatermark); event Reimburse(uint WETHAmt); event EmergencyWithdraw(uint WETHAmt); modifier onlyVault { require(msg.sender == vault, "Only vault"); _; } function initialize(address _WBTCETHVault, address _USDCETHVault, bool _mode) external initializer { WBTCETHVault = IDaoL1Vault(_WBTCETHVault); USDCETHVault = IDaoL1Vault(_USDCETHVault); profitFeePerc = 2000; mode = _mode; WETH.safeApprove(address(router), type(uint).max); WBTC.safeApprove(address(router), type(uint).max); USDC.safeApprove(address(router), type(uint).max); WBTCETH.safeApprove(address(WBTCETHVault), type(uint).max); WBTCETH.safeApprove(address(router), type(uint).max); USDCETH.safeApprove(address(USDCETHVault), type(uint).max); USDCETH.safeApprove(address(router), type(uint).max); } function invest(uint WETHAmt) external onlyVault { WETH.safeTransferFrom(vault, address(this), WETHAmt); uint halfWETHAmt = WETHAmt / 2; if (mode) { // Attack uint WBTCAmt = swap2(address(WETH), address(WBTC), halfWETHAmt, 0); (,,uint WBTCETHAmt) = router.addLiquidity( address(WBTC), address(WETH), WBTCAmt, halfWETHAmt, 0, 0, address(this), block.timestamp ); WBTCETHVault.deposit(WBTCETHAmt); emit InvestWBTCETH(WETHAmt, WBTCETHAmt); } else { // Defence uint USDCAmt = swap2(address(WETH), address(USDC), halfWETHAmt, 0); (,,uint USDCETHAmt) = router.addLiquidity( address(USDC), address(WETH), USDCAmt, halfWETHAmt, 0, 0, address(this), block.timestamp ); USDCETHVault.deposit(USDCETHAmt); emit InvestUSDCETH(WETHAmt, USDCETHAmt); } } /// @param amount Amount to withdraw in USD function withdraw(uint amount, uint[] calldata tokenPrice) external onlyVault returns (uint WETHAmt) { uint sharePerc = amount * 1e18 / getAllPoolInUSD(); if (mode) WETHAmt = withdrawWBTCETH(sharePerc, tokenPrice[1]); else WETHAmt = withdrawUSDCETH(sharePerc, tokenPrice[2]); WETH.safeTransfer(vault, WETHAmt); } function withdrawWBTCETH(uint sharePerc, uint WBTCPriceInETH) private returns (uint) { uint WBTCETHAmt = WBTCETHVault.withdraw(WBTCETHVault.balanceOf(address(this)) * sharePerc / 1e18); (uint WBTCAmt, uint WETHAmt) = router.removeLiquidity( address(WBTC), address(WETH), WBTCETHAmt, 0, 0, address(this), block.timestamp ); WETHAmt += swap2(address(WBTC), address(WETH), WBTCAmt, WBTCAmt * WBTCPriceInETH / 1e8); emit WithdrawWBTCETH(WBTCETHAmt, WETHAmt); return WETHAmt; } function withdrawUSDCETH(uint sharePerc, uint USDCPriceInETH) private returns (uint) { uint USDCETHAmt = USDCETHVault.withdraw(USDCETHVault.balanceOf(address(this)) * sharePerc / 1e18); (uint USDCAmt, uint WETHAmt) = router.removeLiquidity( address(USDC), address(WETH), USDCETHAmt, 0, 0, address(this), block.timestamp ); WETHAmt += swap2(address(USDC), address(WETH), USDCAmt, USDCAmt * USDCPriceInETH / 1e6); emit WithdrawUSDCETH(USDCETHAmt, WETHAmt); return WETHAmt; } function switchMode(uint[] calldata tokenPrice) external onlyVault { if (mode) { // Attack switch to defence uint WBTCETHAmt = WBTCETHVault.withdraw(WBTCETHVault.balanceOf(address(this))); (uint WBTCAmt, uint WETHAmt) = router.removeLiquidity( address(WBTC), address(WETH), WBTCETHAmt, 0, 0, address(this), block.timestamp ); // tokenPrice[0] = 1 WBTC Price In USDC uint USDCAmt = swap3(address(WBTC), address(USDC), WBTCAmt, WBTCAmt * tokenPrice[0] / 1e8); (,,uint USDCETHAmt) = router.addLiquidity( address(USDC), address(WETH), USDCAmt, WETHAmt, 0, 0, address(this), block.timestamp ); USDCETHVault.deposit(USDCETHAmt); mode = false; emit SwitchMode(WBTCETHAmt, USDCETHAmt, true, false); } else { // Defence switch to attack uint USDCETHAmt = USDCETHVault.withdraw(USDCETHVault.balanceOf(address(this))); (uint USDCAmt, uint WETHAmt) = router.removeLiquidity( address(USDC), address(WETH), USDCETHAmt, 0, 0, address(this), block.timestamp ); // tokenPrice[1] = 1 USDC Price In WBTC uint WBTCAmt = swap3(address(USDC), address(WBTC), USDCAmt, USDCAmt * tokenPrice[1] / 1e6); (,,uint WBTCETHAmt) = router.addLiquidity( address(WBTC), address(WETH), WBTCAmt, WETHAmt, 0, 0, address(this), block.timestamp ); WBTCETHVault.deposit(WBTCETHAmt); mode = true; emit SwitchMode(USDCETHAmt, WBTCETHAmt, false, true); } } function collectProfitAndUpdateWatermark() public onlyVault returns (uint fee) { uint currentWatermark = getAllPoolInUSD(); uint lastWatermark = watermark; if (currentWatermark > lastWatermark) { uint profit = currentWatermark - lastWatermark; fee = profit * profitFeePerc / 10000; watermark = currentWatermark; } emit CollectProfitAndUpdateWatermark(currentWatermark, lastWatermark, fee); } /// @param signs True for positive, false for negative function adjustWatermark(uint amount, bool signs) external onlyVault { uint lastWatermark = watermark; watermark = signs == true ? watermark + amount : watermark - amount; emit AdjustWatermark(watermark, lastWatermark); } /// @param amount Amount to reimburse to vault contract in ETH function reimburse(uint amount) external onlyVault returns (uint WETHAmt) { if (mode) withdrawWBTCETH(amount * 1e18 / getWBTCETHPoolInETH(), 0); else withdrawUSDCETH(amount * 1e18 / getUSDCETHPoolInETH(), 0); WETHAmt = WETH.balanceOf(address(this)); WETH.safeTransfer(vault, WETHAmt); emit Reimburse(WETHAmt); } function emergencyWithdraw() external onlyVault { // 1e18 == 100% of share if (mode) withdrawWBTCETH(1e18, 0); else withdrawUSDCETH(1e18, 0); uint WETHAmt = WETH.balanceOf(address(this)); WETH.safeTransfer(vault, WETHAmt); watermark = 0; emit EmergencyWithdraw(WETHAmt); } function swap2(address from, address to, uint amount, uint amountOutMin) private returns (uint) { address[] memory path = new address[](2); path[0] = from; path[1] = to; return router.swapExactTokensForTokens(amount, amountOutMin, path, address(this), block.timestamp)[1]; } function swap3(address from, address to, uint amount, uint amountOutMin) private returns (uint) { address[] memory path = new address[](3); path[0] = from; path[1] = address(WETH); path[2] = to; return router.swapExactTokensForTokens(amount, amountOutMin, path, address(this), block.timestamp)[2]; } function setVault(address _vault) external { require(vault == address(0), "Vault set"); vault = _vault; } function setProfitFeePerc(uint _profitFeePerc) external onlyVault { profitFeePerc = _profitFeePerc; } function getPath(address tokenA, address tokenB) private pure returns (address[] memory path) { path = new address[](2); path[0] = tokenA; path[1] = tokenB; } function getWBTCETHPoolInETH() private view returns (uint) { uint WBTCETHVaultPool = WBTCETHVault.getAllPoolInETH(); if (WBTCETHVaultPool == 0) return 0; return WBTCETHVaultPool * WBTCETHVault.balanceOf(address(this)) / WBTCETHVault.totalSupply(); } function getUSDCETHPoolInETH() private view returns (uint) { uint USDCETHVaultPool = USDCETHVault.getAllPoolInETH(); if (USDCETHVaultPool == 0) return 0; return USDCETHVaultPool * USDCETHVault.balanceOf(address(this)) / USDCETHVault.totalSupply(); } /// @notice This function return only farms TVL in ETH function getAllPoolInETH() public view returns (uint) { if (mode) return getWBTCETHPoolInETH(); // Attack else return getUSDCETHPoolInETH(); // Defence } function getAllPoolInUSD() public view returns (uint) { uint ETHPriceInUSD = uint(IChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419).latestAnswer()); // 8 decimals require(ETHPriceInUSD > 0, "ChainLink error"); return getAllPoolInETH() * ETHPriceInUSD / 1e8; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; 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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@param amount Amount to reimburse to vault contract in ETH
function reimburse(uint amount) external onlyVault returns (uint WETHAmt) { if (mode) withdrawWBTCETH(amount * 1e18 / getWBTCETHPoolInETH(), 0); else withdrawUSDCETH(amount * 1e18 / getUSDCETHPoolInETH(), 0); WETHAmt = WETH.balanceOf(address(this)); WETH.safeTransfer(vault, WETHAmt); emit Reimburse(WETHAmt); }
5,716,869
[ 1, 8949, 16811, 358, 283, 381, 70, 295, 307, 358, 9229, 6835, 316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 381, 70, 295, 307, 12, 11890, 3844, 13, 3903, 1338, 12003, 1135, 261, 11890, 678, 1584, 19191, 1010, 13, 288, 203, 3639, 309, 261, 3188, 13, 598, 9446, 59, 38, 56, 1441, 2455, 12, 8949, 380, 404, 73, 2643, 342, 13876, 38, 56, 1441, 2455, 2864, 382, 1584, 44, 9334, 374, 1769, 203, 3639, 469, 598, 9446, 3378, 40, 1441, 2455, 12, 8949, 380, 404, 73, 2643, 342, 336, 3378, 40, 1441, 2455, 2864, 382, 1584, 44, 9334, 374, 1769, 203, 3639, 678, 1584, 19191, 1010, 273, 678, 1584, 44, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 678, 1584, 44, 18, 4626, 5912, 12, 26983, 16, 678, 1584, 19191, 1010, 1769, 203, 3639, 3626, 868, 381, 70, 295, 307, 12, 59, 1584, 19191, 1010, 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 ]
./full_match/1/0xdf8d9c9f46785E1e333fdb67E1BFc06a4Ad33A99/sources/@iden3/contracts/validators/CredentialAtomicQueryValidator.sol
The non-empty state is returned, and it's not equal to the state that the user has provided. Get the time of the latest state and compare it to the transition time of state provided by the user.
function _checkClaimNonRevState(uint256 _id, uint256 _claimNonRevState) internal view { IState.StateInfo memory claimNonRevStateInfo = state.getStateInfoById(_id); if (claimNonRevStateInfo.state == 0) { require( GenesisUtils.isGenesisState(_id, _claimNonRevState), "Non-Revocation state isn't in state contract and not genesis" ); if (claimNonRevStateInfo.state != _claimNonRevState) { IState.StateInfo memory claimNonRevLatestStateInfo = state.getStateInfoByIdAndState( _id, _claimNonRevState ); if (claimNonRevLatestStateInfo.id == 0 || claimNonRevLatestStateInfo.id != _id) { revert("state in transition info contains invalid id"); } if (claimNonRevLatestStateInfo.replacedAtTimestamp == 0) { revert("Non-Latest state doesn't contain replacement information"); } if ( block.timestamp - claimNonRevLatestStateInfo.replacedAtTimestamp > revocationStateExpirationTime ) { revert("Non-Revocation state of Issuer expired"); } } } }
4,960,161
[ 1, 1986, 1661, 17, 5531, 919, 353, 2106, 16, 471, 518, 1807, 486, 3959, 358, 326, 919, 716, 326, 729, 711, 2112, 18, 968, 326, 813, 434, 326, 4891, 919, 471, 3400, 518, 358, 326, 6007, 813, 434, 919, 2112, 635, 326, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 389, 1893, 9762, 3989, 10070, 1119, 12, 11890, 5034, 389, 350, 16, 2254, 5034, 389, 14784, 3989, 10070, 1119, 13, 2713, 1476, 288, 203, 3639, 467, 1119, 18, 1119, 966, 3778, 7516, 3989, 10070, 1119, 966, 273, 919, 18, 588, 1119, 966, 5132, 24899, 350, 1769, 203, 203, 3639, 309, 261, 14784, 3989, 10070, 1119, 966, 18, 2019, 422, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 31637, 1989, 18, 291, 7642, 16786, 1119, 24899, 350, 16, 389, 14784, 3989, 10070, 1119, 3631, 203, 7734, 315, 3989, 17, 28691, 919, 5177, 1404, 316, 919, 6835, 471, 486, 21906, 6, 203, 5411, 11272, 203, 5411, 309, 261, 14784, 3989, 10070, 1119, 966, 18, 2019, 480, 389, 14784, 3989, 10070, 1119, 13, 288, 203, 7734, 467, 1119, 18, 1119, 966, 3778, 7516, 3989, 10070, 18650, 1119, 966, 273, 919, 18, 588, 1119, 966, 5132, 1876, 1119, 12, 203, 10792, 389, 350, 16, 203, 10792, 389, 14784, 3989, 10070, 1119, 203, 7734, 11272, 203, 203, 7734, 309, 261, 14784, 3989, 10070, 18650, 1119, 966, 18, 350, 422, 374, 747, 7516, 3989, 10070, 18650, 1119, 966, 18, 350, 480, 389, 350, 13, 288, 203, 10792, 15226, 2932, 2019, 316, 6007, 1123, 1914, 2057, 612, 8863, 203, 7734, 289, 203, 203, 7734, 309, 261, 14784, 3989, 10070, 18650, 1119, 966, 18, 2079, 72, 861, 4921, 422, 374, 13, 288, 203, 10792, 15226, 2932, 3989, 17, 18650, 919, 3302, 1404, 912, 6060, 1779, 8863, 203, 7734, 289, 203, 203, 7734, 309, 261, 203, 10792, 1203, 18, 5508, 2 ]