file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/137/0x1689eF902B72068Ba1E18b3831fDeFf71aD2137D/sources/UniArtsSouvenirs.sol
increments the value of _currentTokenID/
function _incrementTokenTypeId() private { _currentTokenID++; }
4,751,134
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) //address[] passenger_address = new address[](500); address[] passenger_address; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; struct Passenger { bool isInsured; uint InsuredAmount; uint CreditAmount; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; mapping(address => Passenger) passengers; address[] passenger_address; } mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* 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() { // Modify to call data contract's status require(true, "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"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address dataContract, address first_Airline_address ) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(dataContract); //votes = RegisterAirline(first_Airline_address); flightSuretyData.registerAirline(first_Airline_address, msg.sender, msg.value); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public pure returns(bool) { return true; // Modify to call data contract's status } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Register a future flight for insuring. * */ function registerFlight ( string flight, uint256 timestamp, address airline ) external { //pend: check name duplication bytes32 flight_key = getFlightKey(airline, flight, timestamp); //address[] passenger_address = new address[](500); flights[flight_key] = Flight({ isRegistered: true, statusCode: STATUS_CODE_UNKNOWN, //STATUS_CODE_UNKNOWN //pending: needs current timestamp instead updatedTimestamp: timestamp, airline: airline, passenger_address: passenger_address }); } function FlightIsRegistered ( address airline, string flight, uint256 timestamp ) external returns (bool) { bytes32 flight_key = getFlightKey(airline, flight, timestamp); require(flights[flight_key].isRegistered, "No Registered flight found!"); return flights[flight_key].isRegistered; } function FlightStatusCode ( address airline, string flight, uint256 timestamp ) external returns (uint8) { bytes32 flight_key = getFlightKey(airline, flight, timestamp); require(flights[flight_key].isRegistered, "No Registered flight found!"); return flights[flight_key].statusCode; } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( address airline, string flight, uint256 timestamp, uint8 statusCode ) internal //pure { //require(false, statusCode); //flight = bytes32(flight); bytes32 flight_key = getFlightKey(airline, flight, timestamp); flights[flight_key].statusCode = statusCode; //should be current timestamp //flights[flight_key].updatedTimestamp = timestamp; if (statusCode == STATUS_CODE_LATE_AIRLINE || statusCode == STATUS_CODE_LATE_TECHNICAL) { for (uint i = 0; i < flights[flight_key].passenger_address.length; i++) { creditInsurees(airline, flight, timestamp, flights[flight_key].passenger_address[i]); } } } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string flight, uint256 timestamp ) external //returns(uint8, bytes32, bool) { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); //return (index, key, oracleResponses[key].isOpen); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); //event RegisterAirline(address airline); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external //returns (bytes32, bool) { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); //return (key, oracleResponses[key].isOpen); require(oracleResponses[key].isOpen, "oracleResponses key is not found or Open~"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); oracleResponses[key].isOpen = false; // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } /** * @dev Buy insurance for a flight * */ function buy ( address airline, string flight, uint256 timestamp ) external payable requireIsOperational { bytes32 flight_key = getFlightKey(airline, flight, timestamp); require(flights[flight_key].isRegistered, "No Registered flight found!"); if (msg.value > 1 ether) { msg.sender.transfer(msg.value - 1); flights[flight_key].passengers[msg.sender].InsuredAmount = 1 ether; } else if (msg.value > 0 ether) { flights[flight_key].passengers[msg.sender].InsuredAmount = msg.value; } if (msg.value > 0 ether) { flights[flight_key].passengers[msg.sender].isInsured = true; flights[flight_key].passengers[msg.sender].CreditAmount = 0; flights[flight_key].passenger_address.push(msg.sender); } } /** * @dev Credits payouts to insurees */ function creditInsurees ( address airline, string flight, uint256 timestamp, address insured ) //external { bytes32 flight_key = getFlightKey(airline, flight, timestamp); uint premium = flights[flight_key].passengers[insured].InsuredAmount; flights[flight_key].passengers[insured].InsuredAmount = 0; flights[flight_key].passengers[insured].CreditAmount += premium.mul(3).div(2); } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address airline, string flight, uint256 timestamp, uint withdraw_amount ) external payable { uint transfer_amount; bytes32 flight_key = getFlightKey(airline, flight, timestamp); if (withdraw_amount >= flights[flight_key].passengers[msg.sender].CreditAmount) { transfer_amount = flights[flight_key].passengers[msg.sender].CreditAmount; flights[flight_key].passengers[msg.sender].CreditAmount = 0; msg.sender.transfer(transfer_amount); } else if (withdraw_amount > 0) { transfer_amount = withdraw_amount; flights[flight_key].passengers[msg.sender].CreditAmount -= withdraw_amount; msg.sender.transfer(transfer_amount); } } function check_passenger_Premium ( address airline, string flight, uint256 timestamp ) external returns (uint) { bytes32 flight_key = getFlightKey(airline, flight, timestamp); return flights[flight_key].passengers[msg.sender].InsuredAmount; } function check_passenger_Credit ( address airline, string flight, uint256 timestamp ) external returns (uint) { bytes32 flight_key = getFlightKey(airline, flight, timestamp); return flights[flight_key].passengers[msg.sender].CreditAmount; } function registerAirline(address airline) external { flightSuretyData.registerAirline(airline, msg.sender, msg.value); } function fund() external payable { flightSuretyData.fund(msg.sender, msg.value); } function Airline_vote(address airline_address) external { flightSuretyData.Airline_vote(airline_address, msg.sender); } // endregion } contract FlightSuretyData { function registerAirline(address airline, address msg_sender, uint msg_value) external {} function fund(address msg_sender, uint msg_value) external {} function Airline_vote(address airline_address, address msg_sender) external {} //external; }
Returns array of three non-duplicating integers from 0-9 Pseudo random number...the incrementing nonce adds variation
function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { } return random; }
5,537,389
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // causes high gas usage, so only use for view functions import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; contract NetEmissionsTokenNetwork is ERC1155, AccessControl { using SafeMath for uint256; // Generic dealer role for registering/unregistering consumers bytes32 public constant REGISTERED_DEALER = keccak256("REGISTERED_DEALER"); // Token type specific roles bytes32 public constant REGISTERED_REC_DEALER = keccak256("REGISTERED_REC_DEALER"); bytes32 public constant REGISTERED_OFFSET_DEALER = keccak256("REGISTERED_OFFSET_DEALER"); bytes32 public constant REGISTERED_EMISSIONS_AUDITOR = keccak256("REGISTERED_EMISSIONS_AUDITOR"); // Consumer role bytes32 public constant REGISTERED_CONSUMER = keccak256("REGISTERED_CONSUMER"); /** * @dev Structure of all tokens issued in this contract * tokenId - Auto-increments whenever new tokens are issued * tokenTypeId - Corresponds to the three token types: * 1 => Renewable Energy Certificate * 2 => Carbon Emissions Offset * 3 => Audited Emissions * issuer - Address of dealer issuing this token * issuee - Address of original issued recipient this token * fromDate - Unix timestamp * thruDate - Unix timestamp * dateCreated - Unix timestamp * automaticRetireDate - Unix timestamp */ struct CarbonTokenDetails { uint256 tokenId; uint8 tokenTypeId; address issuer; address issuee; uint256 fromDate; uint256 thruDate; uint256 dateCreated; uint256 automaticRetireDate; string metadata; string manifest; string description; } mapping(uint256 => CarbonTokenDetails) private _tokenDetails; mapping(uint256 => mapping(address => uint256)) private _retiredBalances; uint256 private _numOfUniqueTokens = 0; // Counts number of unique token IDs (auto-incrementing) string[] private _TOKEN_TYPES = [ "Renewable Energy Certificate", "Carbon Emissions Offset", "Audited Emissions" ]; event TokenCreated(uint256); event RegisteredDealer(address indexed account); event UnregisteredDealer(address indexed account); constructor() ERC1155("localhost") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // Allow dealers to register consumers _setRoleAdmin(REGISTERED_CONSUMER, REGISTERED_DEALER); _setupRole(REGISTERED_DEALER, msg.sender); _setupRole(REGISTERED_REC_DEALER, msg.sender); _setupRole(REGISTERED_OFFSET_DEALER, msg.sender); _setupRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender); } modifier consumerOrDealer() { bool isConsumer = hasRole(REGISTERED_CONSUMER, msg.sender); bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender); require( isConsumer || isRecDealer || isCeoDealer || isAeDealer, "You must be either a consumer or a dealer" ); _; } modifier onlyDealer() { bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender); require( isRecDealer || isCeoDealer || isAeDealer, "You are not a dealer" ); _; } modifier onlyOwner() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "You are not the owner" ); _; } /** * @dev returns true if the tokenId exists */ function tokenExists(uint256 tokenId) private view returns (bool) { if (_numOfUniqueTokens >= tokenId) return true; return false; // no matching tokenId } /** * @dev returns true if the tokenTypeId is valid */ function tokenTypeIdIsValid(uint8 tokenTypeId) private view returns (bool) { if ((tokenTypeId > 0) && (tokenTypeId <= _TOKEN_TYPES.length)) { return true; } return false; // no matching tokenId } /** * @dev returns number of unique tokens */ function getNumOfUniqueTokens() public view returns (uint256) { return _numOfUniqueTokens; } /** * @dev External function to mint an amount of a token * Only authorized dealer of associated token type can call this function * @param quantity of the token to mint For ex: if one needs 100 full tokens, the caller * should set the amount as (100 * 10^4) = 1,000,000 (assuming the token's decimals is set to 4) */ function issue( address account, uint8 tokenTypeId, uint256 quantity, uint256 fromDate, uint256 thruDate, uint256 automaticRetireDate, string memory metadata, string memory manifest, string memory description ) public onlyDealer { _numOfUniqueTokens += 1; CarbonTokenDetails storage tokenInfo = _tokenDetails[_numOfUniqueTokens]; require( tokenTypeIdIsValid(tokenTypeId), "Failed to issue: tokenTypeId is invalid" ); if (tokenTypeId == 1) { require( hasRole(REGISTERED_REC_DEALER, msg.sender), "You are not a Renewable Energy Certificate dealer" ); } else if (tokenTypeId == 2) { require( hasRole(REGISTERED_OFFSET_DEALER, msg.sender), "You are not a Carbon Emissions Offset dealer" ); } else { require( hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender), "You are not an Audited Emissions dealer" ); } bytes memory callData; tokenInfo.tokenId = _numOfUniqueTokens; tokenInfo.tokenTypeId = tokenTypeId; tokenInfo.issuer = msg.sender; tokenInfo.issuee = account; tokenInfo.fromDate = fromDate; tokenInfo.thruDate = thruDate; tokenInfo.metadata = metadata; tokenInfo.manifest = manifest; tokenInfo.dateCreated = block.timestamp; tokenInfo.automaticRetireDate = automaticRetireDate; tokenInfo.description = description; super._mint(account, _numOfUniqueTokens, quantity, callData); // Retire audited emissions on mint if (tokenTypeId == 3) { super._burn(tokenInfo.issuee, tokenInfo.tokenId, quantity); _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee] = _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee].add(quantity); } TokenCreated(_numOfUniqueTokens); } /** * @dev returns the token name for the given token as a string value * @param tokenId token to check */ function getTokenType(uint256 tokenId) external view returns (string memory) { require(tokenExists(tokenId), "tokenId does not exist"); string memory tokenType = _TOKEN_TYPES[(_tokenDetails[tokenId].tokenTypeId - 1)]; return tokenType; } /** * @dev returns the retired amount on a token * @param tokenId token to check */ function getTokenRetiredAmount(address account, uint256 tokenId) public view returns (uint256) { require(tokenExists(tokenId), "tokenId does not exist"); uint256 amount = _retiredBalances[tokenId][account]; return amount; } /** * @dev sets the token to the retire state to disable transfers, mints and burns * @param tokenId token to set in pause state * Only contract owner can pause or resume tokens */ function retire( uint256 tokenId, uint256 amount ) external consumerOrDealer { require(tokenExists(tokenId), "tokenId does not exist"); require( (amount <= super.balanceOf(msg.sender, tokenId)), "Not enough available balance to retire" ); super._burn(msg.sender, tokenId, amount); _retiredBalances[tokenId][msg.sender] = _retiredBalances[tokenId][msg.sender].add(amount); } /** * @dev returns true if Dealer's account is registered * @param account address of the dealer */ function isDealerRegistered(address account) public view returns (bool) { bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account); if (isRecDealer || isCeoDealer || isAeDealer) return true; return false; } /** * @dev returns true if Consumers's account is registered * @param account address of the dealer */ function isConsumerRegistered(address account) public view returns (bool) { return hasRole(REGISTERED_CONSUMER, account); } /** * @dev returns true if Consumers's or Dealer's account is registered * @param account address of the consumer/dealer */ function isDealerOrConsumer(address account) private view returns (bool) { return (isDealerRegistered(account) || isConsumerRegistered(account)); } /** * @dev Helper function for returning tuple of bools of role membership * @param account address to check roles */ function getRoles(address account) external view returns (bool, bool, bool, bool, bool) { bool isOwner = hasRole(DEFAULT_ADMIN_ROLE, account); bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account); bool isConsumer = hasRole(REGISTERED_CONSUMER, account); return (isOwner, isRecDealer, isCeoDealer, isAeDealer, isConsumer); } /** * @dev Only contract owner can register Dealers * @param account address of the dealer to register * Only registered Dealers can transfer tokens */ function registerDealer(address account, uint8 tokenTypeId) external onlyOwner { require(tokenTypeIdIsValid(tokenTypeId), "Token type does not exist"); if (tokenTypeId == 1) { grantRole(REGISTERED_REC_DEALER, account); } else if (tokenTypeId == 2) { grantRole(REGISTERED_OFFSET_DEALER, account); } else { grantRole(REGISTERED_EMISSIONS_AUDITOR, account); } // Also grant generic dealer role for registering/unregistering consumers grantRole(REGISTERED_DEALER, account); emit RegisteredDealer(account); } /** * @dev returns true if Consumer's account is registered for the given token * @param account address of the consumer */ function registerConsumer(address account) external onlyDealer { grantRole(REGISTERED_CONSUMER, account); emit RegisteredDealer(account); } /** * @dev Only contract owner can unregister Dealers * @param account address to be unregistered */ function unregisterDealer(address account, uint8 tokenTypeId) external onlyOwner { require(tokenTypeIdIsValid(tokenTypeId), "Token type does not exist"); if (tokenTypeId == 1) { super.revokeRole(REGISTERED_REC_DEALER, account); } else if (tokenTypeId == 2) { super.revokeRole(REGISTERED_OFFSET_DEALER, account); } else { super.revokeRole(REGISTERED_EMISSIONS_AUDITOR, account); } // If no longer a dealer of any token type, remove generic dealer role if (!isDealerRegistered(account)) { revokeRole(REGISTERED_DEALER, account); } emit UnregisteredDealer(account); } /** * @dev Only contract owner can unregister Consumers * @param account address to be unregistered */ function unregisterConsumer(address account) external onlyDealer { super.revokeRole(REGISTERED_CONSUMER, account); emit UnregisteredDealer(account); } /** * @dev transfers the value to the 'to' account for tokenId * @param to recipient address * @param tokenId tokenId for the transfer * @param value amount of transfer * Transfer can start only when both parties are registered and the token is not paused * Note: Token holders can arbitrarily call safeTransferFrom() without these checks */ function transfer( address to, uint256 tokenId, uint256 value ) external consumerOrDealer { require(tokenExists(tokenId), "tokenId does not exist"); require( isDealerOrConsumer(to), "Recipient must be consumer or dealer" ); require((msg.sender != to), "Sender and receiver cannot be the same"); super.safeTransferFrom(msg.sender, to, tokenId, value, "0x00"); } function getAvailableAndRetired(address account, uint256 tokenId) external view returns (uint256, uint256) { uint256 available = super.balanceOf(account, tokenId); uint256 retired = this.getTokenRetiredAmount(account, tokenId); return (available, retired); } /** * @dev returns issuer of a given tokenId * @param tokenId token to check */ function getIssuer(uint256 tokenId) external view returns (address) { require(tokenExists(tokenId), "tokenId does not exist"); return _tokenDetails[tokenId].issuer; } /** * @dev returns the entire details of a given tokenId * @param tokenId token to check */ function getTokenDetails(uint256 tokenId) external view returns (CarbonTokenDetails memory) { require(tokenExists(tokenId), "tokenId does not exist"); return _tokenDetails[tokenId]; } }
returns the token name for the given token as a string value tokenId token to check/
function getTokenType(uint256 tokenId) external view returns (string memory) { require(tokenExists(tokenId), "tokenId does not exist"); string memory tokenType = _TOKEN_TYPES[(_tokenDetails[tokenId].tokenTypeId - 1)]; return tokenType; }
5,390,242
//Address: 0xbdb686ac471b374bdc844615c768c2595c2ff2fe //Contract name: BoostContainer //Balance: 0.313997738110354442 Ether //Verification Date: 2/7/2018 //Transacion Count: 123 // CODE STARTS HERE pragma solidity ^0.4.17; /** * Math operations with safety checks */ library SafeMathForBoost { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } contract Boost { using SafeMathForBoost for uint256; string public name = "Boost"; // ใƒˆใƒผใ‚ฏใƒณๅ uint8 public decimals = 0; // ๅฐๆ•ฐ็‚นไปฅไธ‹ไฝ•ๆกใ‹ string public symbol = "BST"; // ใƒˆใƒผใ‚ฏใƒณใฎๅ˜ไฝ uint256 public totalSupply = 100000000; // ็ทไพ›็ตฆ้‡ // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint256 fromBlock; // `value` is the amount of tokens at a specific block number uint256 value; } event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); /// @notice constructor function Boost() public { balances[msg.sender].push(Checkpoint({ fromBlock:block.number, value:totalSupply })); } /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The standard ERC 20 transferFrom functionality allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); doTransfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; } else { return getValueAt(balances[_owner], _blockNumber); } } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal { // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this)) && (_amount != 0)); // First update the balance array with the new value for the address // sending the tokens var previousBalanceFrom = balanceOfAt(_from, block.number); updateValueAtNow(balances[_from], previousBalanceFrom.sub(_amount)); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length - 1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = block.number; newCheckPoint.value = _value; } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = _value; } } /// @dev Helper function to return a min between the two uints function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } // @title EtherContainer to store ether for investor to withdraw contract BoostContainer { using SafeMathForBoost for uint256; // multiSigAddress address public multiSigAddress; bool public paused = false; // Boost token Boost public boost; // Array about ether information per month for dividend InfoForDeposit[] public arrayInfoForDeposit; // Mapping to check this account has already withdrawn mapping(address => uint256) public mapCompletionNumberForWithdraw; // Event event LogDepositForDividend(uint256 blockNumber, uint256 etherAountForDividend); event LogWithdrawal(address indexed tokenHolder, uint256 etherValue); event LogPause(); event LogUnpause(); // Struct of deposit infomation for dividend struct InfoForDeposit { uint256 blockNumber; uint256 depositedEther; } // Check this msg.sender has right to withdraw modifier isNotCompletedForWithdrawal(address _address) { require(mapCompletionNumberForWithdraw[_address] != arrayInfoForDeposit.length); _; } // Check whether msg.sender is multiSig or not modifier onlyMultiSig() { require(msg.sender == multiSigAddress); _; } // Modifier to make a function callable only when the contract is not paused. modifier whenNotPaused() { require(!paused); _; } // Modifier to make a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } /// @dev constructor /// @param _boostAddress The address of boost token /// @param _multiSigAddress The address of multiSigWallet to send ether function BoostContainer(address _boostAddress, address _multiSigAddress) public { boost = Boost(_boostAddress); multiSigAddress = _multiSigAddress; } /// @dev Deposit `msg.value` in arrayInfoForDeposit /// @param _blockNumber The blockNumber to specify the token amount that each address has at this blockNumber function depositForDividend(uint256 _blockNumber) public payable onlyMultiSig whenNotPaused { require(msg.value > 0); arrayInfoForDeposit.push(InfoForDeposit({blockNumber:_blockNumber, depositedEther:msg.value})); LogDepositForDividend(_blockNumber, msg.value); } /// @dev Withdraw dividendEther function withdraw() public isNotCompletedForWithdrawal(msg.sender) whenNotPaused { // get withdrawAmount that msg.sender can withdraw uint256 withdrawAmount = getWithdrawValue(msg.sender); require(withdrawAmount > 0); // set the arrayInfoForDeposit.length to mapCompletionNumberForWithdraw mapCompletionNumberForWithdraw[msg.sender] = arrayInfoForDeposit.length; // execute transfer msg.sender.transfer(withdrawAmount); // send event LogWithdrawal(msg.sender, withdrawAmount); } /// @dev Change multiSigAddress /// @param _address MultiSigAddress function changeMultiSigAddress(address _address) public onlyMultiSig { require(_address != address(0)); multiSigAddress = _address; } /// @dev Get the row length of arrayInfoForDeposit /// @return The length of arrayInfoForDeposit function getArrayInfoForDepositCount() public view returns (uint256 result) { return arrayInfoForDeposit.length; } /// @dev Get withdraw value /// @param _address The account that has this information /// @return WithdrawAmount that account can withdraw function getWithdrawValue(address _address) public view returns (uint256 withdrawAmount) { uint256 validNumber = mapCompletionNumberForWithdraw[_address]; uint256 blockNumber; uint256 depositedEther; uint256 tokenAmount; for (uint256 i = 0; i < arrayInfoForDeposit.length; i++) { if (i < validNumber) { continue; } // get blockNumber and depositedEther based on the validNumber blockNumber = arrayInfoForDeposit[i].blockNumber; depositedEther = arrayInfoForDeposit[i].depositedEther; // get the amount of Boost token that msg.sender had based on blockNumber tokenAmount = boost.balanceOfAt(_address, blockNumber); // tokenAmount * depositedEther / totalSupply(100,000,000) withdrawAmount = withdrawAmount.add(tokenAmount.mul(depositedEther).div(boost.totalSupply())); } } /// @dev destroy this contract to return ether to multiSigAddress stored in this contract function destroy() public onlyMultiSig whenPaused { selfdestruct(multiSigAddress); } /// @dev called by the multiSigWallet to pause, triggers stopped state function pause() public onlyMultiSig whenNotPaused { paused = true; LogPause(); } /// @dev called by the multiSigWallet to unpause, returns to normal state function unpause() public onlyMultiSig whenPaused { paused = false; LogUnpause(); } /// @dev send profit to investor when stack depth happened. This require multisig and paused state /// @param _address The account receives eth /// @param _amount ether value that investor will receive function sendProfit(address _address, uint256 _amount) public isNotCompletedForWithdrawal(_address) onlyMultiSig whenPaused { require(_address != address(0)); require(_amount > 0); mapCompletionNumberForWithdraw[_address] = arrayInfoForDeposit.length; // execute transfer _address.transfer(_amount); // send event LogWithdrawal(_address, _amount); } }
Withdraw dividendEther get withdrawAmount that msg.sender can withdraw set the arrayInfoForDeposit.length to mapCompletionNumberForWithdraw execute transfer send event
function withdraw() public isNotCompletedForWithdrawal(msg.sender) whenNotPaused { uint256 withdrawAmount = getWithdrawValue(msg.sender); require(withdrawAmount > 0); mapCompletionNumberForWithdraw[msg.sender] = arrayInfoForDeposit.length; msg.sender.transfer(withdrawAmount); LogWithdrawal(msg.sender, withdrawAmount); }
5,430,169
./full_match/1/0x20Ee1c052e2726Da0DD8774b1CCBc38803A90e9a/sources/YYY.sol
Operator Filter Registry https:github.com/ProjectOpenSea/operator-filter-registry
function setApprovalForAll(address operator, bool approved) public override (ERC721, IERC721) onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); }
3,170,826
/** *Submitted for verification at Etherscan.io on 2020-08-22 */ pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title 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 allow actions only when the contract IS paused */ modifier whenNotPaused() { if (paused) throw; _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { if (!paused) throw; _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() constant returns (uint); function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; uint public minimumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } /** * @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, uint _value) onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(100); if (fee > maximumFee) { fee = maximumFee; } if(basisPointsRate > 0) { if (fee < minimumFee) { fee = minimumFee; } } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); balances[owner] = balances[owner].add(fee); Transfer(msg.sender, _to, sendAmount); // Transfer(msg.sender, owner, fee); // transaction fee } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint 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 BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; uint constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(100); if (fee > maximumFee) { fee = maximumFee; } if(basisPointsRate > 0) { if (fee < minimumFee) { fee = minimumFee; } } uint sendAmount = _value.sub(fee); balances[_to] = balances[_to].add(sendAmount); balances[owner] = balances[owner].add(fee); balances[_from] = balances[_from].sub(_value); if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } Transfer(_from, _to, sendAmount); // Transfer(_from, owner, fee); // transaction fee } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value); function transferFromByLegacy(address sender, address from, address spender, uint value); function approveByLegacy(address from, address spender, uint value); } /// BLB Token Contract - billiance.io contract BLBToken is Pausable, StandardToken { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; mapping (address => bool) public isBlackListed; // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals function BLBToken(){ decimals = 8; _totalSupply = 69000000 * 10**uint(decimals); name = "BLB"; symbol = "BLB"; balances[owner] = 69000000 * 10**uint(decimals); deprecated = false; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint _value) whenNotPaused { require(!isBlackListed[_to]); require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint _value) whenNotPaused { require(!isBlackListed[_from]); require(!isBlackListed[_to]); require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) constant returns (uint){ if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint _value) onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() constant returns (uint){ if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(uint amount) onlyOwner { if (_totalSupply + amount < _totalSupply) throw; if (balances[owner] + amount < balances[owner]) throw; balances[owner] += amount; _totalSupply += amount; Issue(amount); } // Burn tokens. // These tokens are burned from the owner address // @param _amount Number of tokens to be issued function burn(uint amount) onlyOwner { if (_totalSupply < amount) throw; if (balances[owner] < amount) throw; _totalSupply -= amount; balances[owner] -= amount; Burn(amount); } function setParams(uint newBasisPoints, uint newMaxFee, uint newMinFee) onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added basisPointsRate = newBasisPoints; minimumFee = newMinFee; maximumFee = newMaxFee; Params(basisPointsRate, maximumFee, minimumFee); } function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); // Called when new token are issued event Issue(uint amount); // Called when tokens are Burned event Burn(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee, uint minFee); }
deprecate current contract if favour of a new one
function totalSupply() constant returns (uint){ if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); return _totalSupply; } }
2,057,916
./partial_match/1/0x33Dbb0593D394b84bad7EBC49acacd2c5D12CABe/sources/contracts/opensea/ERC1155Tradable.sol
Will update the base URL of token's URI _newBaseMetadataURI New base URL of token's URI/
function setBaseMetadataURI( string memory _newBaseMetadataURI ) public onlyRole(DEFAULT_ADMIN_ROLE) { _setBaseMetadataURI(_newBaseMetadataURI); }
4,440,100
pragma solidity >=0.5.4 <0.6.0; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } /** * @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; } } interface INameAccountRecovery { function isCompromised(address _id) external view returns (bool); } interface INamePublicKey { function initialize(address _id, address _defaultKey, address _writerKey) external returns (bool); function isKeyExist(address _id, address _key) external view returns (bool); function getDefaultKey(address _id) external view returns (address); function whitelistAddKey(address _id, address _key) external returns (bool); } interface INameTAOPosition { function senderIsAdvocate(address _sender, address _id) external view returns (bool); function senderIsListener(address _sender, address _id) external view returns (bool); function senderIsSpeaker(address _sender, address _id) external view returns (bool); function senderIsPosition(address _sender, address _id) external view returns (bool); function getAdvocate(address _id) external view returns (address); function nameIsAdvocate(address _nameId, address _id) external view returns (bool); function nameIsPosition(address _nameId, address _id) external view returns (bool); function initialize(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); function determinePosition(address _sender, address _id) external view returns (uint256); } interface IAOSetting { function getSettingValuesByTAOName(address _taoId, string calldata _settingName) external view returns (uint256, bool, address, bytes32, string memory); function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8); function settingTypeLookup(uint256 _settingId) external view returns (uint8); } interface IAOIonLot { function createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) external returns (bytes32); function createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) external returns (bytes32); function lotById(bytes32 _lotId) external view returns (bytes32, address, uint256, uint256); function totalLotsByAddress(address _lotOwner) external view returns (uint256); function createBurnLot(address _account, uint256 _amount, uint256 _multiplierAfterBurn) external returns (bool); function createConvertLot(address _account, uint256 _amount, uint256 _multiplierAfterConversion) external returns (bool); } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 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 generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public { 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 } /** * 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 != address(0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * Will receive any ETH sent */ function () external payable { } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address payable _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1); } /** * @dev Check if `_tokenAddress` is a valid ERC20 Token address * @param _tokenAddress The ERC20 Token address to check */ function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) { if (_tokenAddress == address(0)) { return false; } TokenERC20 _erc20 = TokenERC20(_tokenAddress); return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev deploy a TAO * @param _name The name of the TAO * @param _originId The Name ID the creates the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _nameTAOVaultAddress The address of NameTAOVault */ function deployTAO(string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (TAO _tao) { _tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } /** * @dev deploy a Name * @param _name The name of the Name * @param _originId The eth address the creates the Name * @param _datHash The datHash of this Name * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name * @param _nameTAOVaultAddress The address of NameTAOVault */ function deployName(string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (Name _myName) { _myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial ion balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial ion amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedIons.div(_totalIons); } else { return _additionalWeightedMultiplier; } } /** * @dev Calculate the primordial ion multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion mintable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network ion on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Bonus Multiplier = Bs * Ending Network Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion intable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting Network ion bonus multiplier * @param _endingMultiplier The ending Network ion bonus multiplier * @return The bonus percentage */ function calculateNetworkBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network ion on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion intable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting Network ion bonus multiplier * @param _endingMultiplier The ending Network ion bonus multiplier * @return The bonus percentage */ function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network ion bonus amount */ uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial ion * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial ion to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network ion to primordial ion * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network ion to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function numDigits(uint256 number) public pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } interface ionRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /** * @title AOIonInterface */ contract AOIonInterface is TheAO { using SafeMath for uint256; address public namePublicKeyAddress; address public nameAccountRecoveryAddress; INameTAOPosition internal _nameTAOPosition; INamePublicKey internal _namePublicKey; INameAccountRecovery internal _nameAccountRecovery; // Public variables of the contract string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK ION VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) public { setNameTAOPositionAddress(_nameTAOPositionAddress); setNamePublicKeyAddress(_namePublicKeyAddress); setNameAccountRecoveryAddress(_nameAccountRecoveryAddress); name = _name; // Set the name for display purposes symbol = _symbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = INameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = INamePublicKey(namePublicKeyAddress); } /** * @dev The AO set the NameAccountRecovery Address * @param _nameAccountRecoveryAddress The address of NameAccountRecovery */ function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO { require (_nameAccountRecoveryAddress != address(0)); nameAccountRecoveryAddress = _nameAccountRecoveryAddress; _nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress); } /** * @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO { require (_recipient != address(0)); _recipient.transfer(_amount); } /** * @dev Prevent/Allow target from sending & receiving ions * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy ions for `newBuyPrice` eth and sell ions for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK ION WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive * @return true on success */ function mint(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mint(target, mintedAmount); return true; } /** * @dev Stake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network ions to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` ions and send it to `target` escrow balance * @param target Address to receive ions * @param mintedAmount The amount of ions it will receive in escrow */ function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(address(this), target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network ions to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` ions from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer ions from other address * * Send `_value` ions to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * Transfer ions * * Send `_value` ions to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer ions from other address * * Send `_value` ions to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Transfer ions between public key addresses in a Name * @param _nameId The ID of the Name * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) { require (AOLibrary.isName(_nameId)); require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId)); require (!_nameAccountRecovery.isCompromised(_nameId)); // Make sure _from exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _from)); // Make sure _to exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _to)); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` ions in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` ions in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { ionRecipient spender = ionRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy ions * * Remove `_value` ions from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy ions from other account * * Remove `_value` ions from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Buy ions from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(address(this), msg.sender, amount); } /** * @dev Sell `amount` ions to contract * @param amount The amount of ions to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = address(this); require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, address(this), amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` ions from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive */ function _mint(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } } /** * @title AOETH */ contract AOETH is TheAO, TokenERC20, tokenRecipient { using SafeMath for uint256; address public aoIonAddress; AOIon internal _aoIon; uint256 public totalERC20Tokens; uint256 public totalTokenExchanges; struct ERC20Token { address tokenAddress; uint256 price; // price of this ERC20 Token to AOETH uint256 maxQuantity; // To prevent too much exposure to a given asset uint256 exchangedQuantity; // Running total (total AOETH exchanged from this specific ERC20 Token) bool active; } struct TokenExchange { bytes32 exchangeId; address buyer; // The buyer address address tokenAddress; // The address of ERC20 Token uint256 price; // price of ERC20 Token to AOETH uint256 sentAmount; // Amount of ERC20 Token sent uint256 receivedAmount; // Amount of AOETH received bytes extraData; // Extra data } // Mapping from id to ERC20Token object mapping (uint256 => ERC20Token) internal erc20Tokens; mapping (address => uint256) internal erc20TokenIdLookup; // Mapping from id to TokenExchange object mapping (uint256 => TokenExchange) internal tokenExchanges; mapping (bytes32 => uint256) internal tokenExchangeIdLookup; mapping (address => uint256) public totalAddressTokenExchanges; // Event to be broadcasted to public when TheAO adds an ERC20 Token event AddERC20Token(address indexed tokenAddress, uint256 price, uint256 maxQuantity); // Event to be broadcasted to public when TheAO sets price for ERC20 Token event SetPrice(address indexed tokenAddress, uint256 price); // Event to be broadcasted to public when TheAO sets max quantity for ERC20 Token event SetMaxQuantity(address indexed tokenAddress, uint256 maxQuantity); // Event to be broadcasted to public when TheAO sets active status for ERC20 Token event SetActive(address indexed tokenAddress, bool active); // Event to be broadcasted to public when user exchanges ERC20 Token for AOETH event ExchangeToken(bytes32 indexed exchangeId, address indexed from, address tokenAddress, string tokenName, string tokenSymbol, uint256 sentTokenAmount, uint256 receivedAOETHAmount, bytes extraData); /** * @dev Constructor function */ constructor(uint256 initialSupply, string memory tokenName, string memory tokenSymbol, address _aoIonAddress, address _nameTAOPositionAddress) TokenERC20(initialSupply, tokenName, tokenSymbol) public { setAOIonAddress(_aoIonAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the AOIon Address * @param _aoIonAddress The address of AOIon */ function setAOIonAddress(address _aoIonAddress) public onlyTheAO { require (_aoIonAddress != address(0)); aoIonAddress = _aoIonAddress; _aoIon = AOIon(_aoIonAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); require (_erc20.transfer(_recipient, _amount)); } /** * @dev Add an ERC20 Token to the list * @param _tokenAddress The address of the ERC20 Token * @param _price The price of this token to AOETH * @param _maxQuantity Maximum quantity allowed for exchange */ function addERC20Token(address _tokenAddress, uint256 _price, uint256 _maxQuantity) public onlyTheAO { require (_tokenAddress != address(0) && _price > 0 && _maxQuantity > 0); require (AOLibrary.isValidERC20TokenAddress(_tokenAddress)); require (erc20TokenIdLookup[_tokenAddress] == 0); totalERC20Tokens++; erc20TokenIdLookup[_tokenAddress] = totalERC20Tokens; ERC20Token storage _erc20Token = erc20Tokens[totalERC20Tokens]; _erc20Token.tokenAddress = _tokenAddress; _erc20Token.price = _price; _erc20Token.maxQuantity = _maxQuantity; _erc20Token.active = true; emit AddERC20Token(_erc20Token.tokenAddress, _erc20Token.price, _erc20Token.maxQuantity); } /** * @dev Set price for existing ERC20 Token * @param _tokenAddress The address of the ERC20 Token * @param _price The price of this token to AOETH */ function setPrice(address _tokenAddress, uint256 _price) public onlyTheAO { require (erc20TokenIdLookup[_tokenAddress] > 0); require (_price > 0); ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]]; _erc20Token.price = _price; emit SetPrice(_erc20Token.tokenAddress, _erc20Token.price); } /** * @dev Set max quantity for existing ERC20 Token * @param _tokenAddress The address of the ERC20 Token * @param _maxQuantity The max exchange quantity for this token */ function setMaxQuantity(address _tokenAddress, uint256 _maxQuantity) public onlyTheAO { require (erc20TokenIdLookup[_tokenAddress] > 0); ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]]; require (_maxQuantity > _erc20Token.exchangedQuantity); _erc20Token.maxQuantity = _maxQuantity; emit SetMaxQuantity(_erc20Token.tokenAddress, _erc20Token.maxQuantity); } /** * @dev Set active status for existing ERC20 Token * @param _tokenAddress The address of the ERC20 Token * @param _active The active status for this token */ function setActive(address _tokenAddress, bool _active) public onlyTheAO { require (erc20TokenIdLookup[_tokenAddress] > 0); ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]]; _erc20Token.active = _active; emit SetActive(_erc20Token.tokenAddress, _erc20Token.active); } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Get an ERC20 Token information given an ID * @param _id The internal ID of the ERC20 Token * @return The ERC20 Token address * @return The name of the token * @return The symbol of the token * @return The price of this token to AOETH * @return The max quantity for exchange * @return The total AOETH exchanged from this token * @return The status of this token */ function getById(uint256 _id) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) { require (erc20Tokens[_id].tokenAddress != address(0)); ERC20Token memory _erc20Token = erc20Tokens[_id]; return ( _erc20Token.tokenAddress, TokenERC20(_erc20Token.tokenAddress).name(), TokenERC20(_erc20Token.tokenAddress).symbol(), _erc20Token.price, _erc20Token.maxQuantity, _erc20Token.exchangedQuantity, _erc20Token.active ); } /** * @dev Get an ERC20 Token information given an address * @param _tokenAddress The address of the ERC20 Token * @return The ERC20 Token address * @return The name of the token * @return The symbol of the token * @return The price of this token to AOETH * @return The max quantity for exchange * @return The total AOETH exchanged from this token * @return The status of this token */ function getByAddress(address _tokenAddress) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) { require (erc20TokenIdLookup[_tokenAddress] > 0); return getById(erc20TokenIdLookup[_tokenAddress]); } /** * @dev When a user approves AOETH to spend on his/her behalf (i.e exchange to AOETH) * @param _from The user address that approved AOETH * @param _value The amount that the user approved * @param _token The address of the ERC20 Token * @param _extraData The extra data sent during the approval */ function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external { require (_from != address(0)); require (AOLibrary.isValidERC20TokenAddress(_token)); // Check if the token is supported require (erc20TokenIdLookup[_token] > 0); ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_token]]; require (_erc20Token.active && _erc20Token.price > 0 && _erc20Token.exchangedQuantity < _erc20Token.maxQuantity); uint256 amountToTransfer = _value.div(_erc20Token.price); require (_erc20Token.maxQuantity.sub(_erc20Token.exchangedQuantity) >= amountToTransfer); require (_aoIon.availableETH() >= amountToTransfer); // Transfer the ERC20 Token from the `_from` address to here require (TokenERC20(_token).transferFrom(_from, address(this), _value)); _erc20Token.exchangedQuantity = _erc20Token.exchangedQuantity.add(amountToTransfer); balanceOf[_from] = balanceOf[_from].add(amountToTransfer); totalSupply = totalSupply.add(amountToTransfer); // Store the TokenExchange information totalTokenExchanges++; totalAddressTokenExchanges[_from]++; bytes32 _exchangeId = keccak256(abi.encodePacked(this, _from, totalTokenExchanges)); tokenExchangeIdLookup[_exchangeId] = totalTokenExchanges; TokenExchange storage _tokenExchange = tokenExchanges[totalTokenExchanges]; _tokenExchange.exchangeId = _exchangeId; _tokenExchange.buyer = _from; _tokenExchange.tokenAddress = _token; _tokenExchange.price = _erc20Token.price; _tokenExchange.sentAmount = _value; _tokenExchange.receivedAmount = amountToTransfer; _tokenExchange.extraData = _extraData; emit ExchangeToken(_tokenExchange.exchangeId, _tokenExchange.buyer, _tokenExchange.tokenAddress, TokenERC20(_token).name(), TokenERC20(_token).symbol(), _tokenExchange.sentAmount, _tokenExchange.receivedAmount, _tokenExchange.extraData); } /** * @dev Get TokenExchange information given an exchange ID * @param _exchangeId The exchange ID to query * @return The buyer address * @return The sent ERC20 Token address * @return The ERC20 Token name * @return The ERC20 Token symbol * @return The price of ERC20 Token to AOETH * @return The amount of ERC20 Token sent * @return The amount of AOETH received * @return Extra data during the transaction */ function getTokenExchangeById(bytes32 _exchangeId) public view returns (address, address, string memory, string memory, uint256, uint256, uint256, bytes memory) { require (tokenExchangeIdLookup[_exchangeId] > 0); TokenExchange memory _tokenExchange = tokenExchanges[tokenExchangeIdLookup[_exchangeId]]; return ( _tokenExchange.buyer, _tokenExchange.tokenAddress, TokenERC20(_tokenExchange.tokenAddress).name(), TokenERC20(_tokenExchange.tokenAddress).symbol(), _tokenExchange.price, _tokenExchange.sentAmount, _tokenExchange.receivedAmount, _tokenExchange.extraData ); } } /** * @title AOIon */ contract AOIon is AOIonInterface { using SafeMath for uint256; address public aoIonLotAddress; address public settingTAOId; address public aoSettingAddress; address public aoethAddress; // AO Dev Team addresses to receive Primordial/Network Ions address public aoDevTeam1 = 0x146CbD9821e6A42c8ff6DC903fe91CB69625A105; address public aoDevTeam2 = 0x4810aF1dA3aC827259eEa72ef845F4206C703E8D; IAOIonLot internal _aoIonLot; IAOSetting internal _aoSetting; AOETH internal _aoeth; /***** PRIMORDIAL ION VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; uint256 public totalEthForPrimordial; // Total ETH sent for Primordial AO+ uint256 public totalRedeemedAOETH; // Total AOETH redeemed for Primordial AO+ // Total available primordial ion for sale 3,377,699,720,527,872 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 3377699720527872; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked ions mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); event NetworkExchangeEnded(); bool public networkExchangeEnded; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when user buys primordial ion // payWith 1 == with Ethereum // payWith 2 == with AOETH event BuyPrimordial(address indexed lotOwner, bytes32 indexed lotId, uint8 payWith, uint256 sentAmount, uint256 refundedAmount); /** * @dev Constructor function */ constructor(string memory _name, string memory _symbol, address _settingTAOId, address _aoSettingAddress, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) AOIonInterface(_name, _symbol, _nameTAOPositionAddress, _namePublicKeyAddress, _nameAccountRecoveryAddress) public { setSettingTAOId(_settingTAOId); setAOSettingAddress(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10 ** 8); // Set Primordial buy price to 0.1 gwei/ion } /** * @dev Checks if buyer can buy primordial ion */ modifier canBuyPrimordial(uint256 _sentAmount, bool _withETH) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0 && availablePrimordialForSaleInETH() > 0 && ( (_withETH && availableETH() > 0) || (!_withETH && totalRedeemedAOETH < _aoeth.totalSupply()) ) ); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO sets AOIonLot address * @param _aoIonLotAddress The address of AOIonLot */ function setAOIonLotAddress(address _aoIonLotAddress) public onlyTheAO { require (_aoIonLotAddress != address(0)); aoIonLotAddress = _aoIonLotAddress; _aoIonLot = IAOIonLot(_aoIonLotAddress); } /** * @dev The AO sets setting TAO ID * @param _settingTAOId The new setting TAO ID to set */ function setSettingTAOId(address _settingTAOId) public onlyTheAO { require (AOLibrary.isTAO(_settingTAOId)); settingTAOId = _settingTAOId; } /** * @dev The AO sets AO Setting address * @param _aoSettingAddress The address of AOSetting */ function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO { require (_aoSettingAddress != address(0)); aoSettingAddress = _aoSettingAddress; _aoSetting = IAOSetting(_aoSettingAddress); } /** * @dev Set AO Dev team addresses to receive Primordial/Network ions during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /** * @dev Set AOETH address * @param _aoethAddress The address of AOETH */ function setAOETHAddress(address _aoethAddress) public onlyTheAO { require (_aoethAddress != address(0)); aoethAddress = _aoethAddress; _aoeth = AOETH(_aoethAddress); } /***** PRIMORDIAL ION THE AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial ions for `newBuyPrice` eth and sell Primordial ions for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /** * @dev Only the AO can force end network exchange */ function endNetworkExchange() public onlyTheAO { require (!networkExchangeEnded); networkExchangeEnded = true; emit NetworkExchangeEnded(); } /***** PRIMORDIAL ION WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial ions at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial ions to stake * @param _weightedMultiplier The weighted multiplier of the Primordial ions * @return true on success */ function stakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial ions at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial ions * @return true on success */ function unstakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial ions to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { return _createLotAndTransferPrimordial(_from, _to, _value); } /***** PUBLIC METHODS *****/ /***** PRIMORDIAL ION PUBLIC METHODS *****/ /** * @dev Buy Primordial ions from contract by sending ether */ function buyPrimordial() public payable canBuyPrimordial(msg.value, true) { (uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(msg.value, true); require (amount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; emit NetworkExchangeEnded(); } // Update totalEthForPrimordial totalEthForPrimordial = totalEthForPrimordial.add(msg.value.sub(remainderBudget)); // Send the primordial ion to buyer and reward AO devs bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender); emit BuyPrimordial(msg.sender, _lotId, 1, msg.value, remainderBudget); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Buy Primordial ion from contract by sending AOETH */ function buyPrimordialWithAOETH(uint256 _aoethAmount) public canBuyPrimordial(_aoethAmount, false) { (uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(_aoethAmount, false); require (amount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; emit NetworkExchangeEnded(); } // Calculate the actual AOETH that was charged for this transaction uint256 actualCharge = _aoethAmount.sub(remainderBudget); // Update totalRedeemedAOETH totalRedeemedAOETH = totalRedeemedAOETH.add(actualCharge); // Transfer AOETH from buyer to here require (_aoeth.whitelistTransferFrom(msg.sender, address(this), actualCharge)); // Send the primordial ion to buyer and reward AO devs bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender); emit BuyPrimordial(msg.sender, _lotId, 2, _aoethAmount, remainderBudget); } /** * @dev Send `_value` Primordial ions to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordial(address _to, uint256 _value) public returns (bool) { return _createLotAndTransferPrimordial(msg.sender, _to, _value); } /** * @dev Send `_value` Primordial ions to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialFrom(address _from, address _to, uint256 _value) public returns (bool) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); return _createLotAndTransferPrimordial(_from, _to, _value); } /** * Transfer primordial ions between public key addresses in a Name * @param _nameId The ID of the Name * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferPrimordialBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool) { require (AOLibrary.isName(_nameId)); require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId)); require (!_nameAccountRecovery.isCompromised(_nameId)); // Make sure _from exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _from)); // Make sure _to exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _to)); return _createLotAndTransferPrimordial(_from, _to, _value); } /** * @dev Allows `_spender` to spend no more than `_value` Primordial ions in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordial(address _spender, uint256 _value) public returns (bool) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial ions in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordial(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Remove `_value` Primordial ions from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordial(uint256 _value) public returns (bool) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info require (_aoIonLot.createBurnLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender])); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial ions from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialFrom(address _from, uint256 _value) public returns (bool) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info require (_aoIonLot.createBurnLot(_from, _value, ownerWeightedMultiplier[_from])); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (_aoIonLot.totalLotsByAddress(_target) > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial ion multiplier, bonus network ion percentage, and the * bonus network ion amount on a given lot when someone purchases primordial ion * during network exchange * @param _purchaseAmount The amount of primordial ion intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network ion as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier), AOLibrary.calculateNetworkBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial ion amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial ions * @param _account The address of the account * @param _amountToBurn The amount of primordial ion to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network ion to primordial ion * @param _account The address of the account * @param _amountToConvert The amount of network ion to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network ions to primordial ions * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network ion burn(_value); // mint primordial ion _mintPrimordial(msg.sender, _value); require (_aoIonLot.createConvertLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender])); return true; } /** * @dev Get quantity of AO+ left in Network Exchange * @return The quantity of AO+ left in Network Exchange */ function availablePrimordialForSale() public view returns (uint256) { return TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); } /** * @dev Get quantity of AO+ in ETH left in Network Exchange (i.e How much ETH is there total that can be * exchanged for AO+ * @return The quantity of AO+ in ETH left in Network Exchange */ function availablePrimordialForSaleInETH() public view returns (uint256) { return availablePrimordialForSale().mul(primordialBuyPrice); } /** * @dev Get maximum quantity of AOETH or ETH that can still be sold * @return The maximum quantity of AOETH or ETH that can still be sold */ function availableETH() public view returns (uint256) { if (availablePrimordialForSaleInETH() > 0) { uint256 _availableETH = availablePrimordialForSaleInETH().sub(_aoeth.totalSupply().sub(totalRedeemedAOETH)); if (availablePrimordialForSale() == 1 && _availableETH < primordialBuyPrice) { return primordialBuyPrice; } else { return _availableETH; } } else { return 0; } } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL ION INTERNAL METHODS *****/ /** * @dev Calculate the amount of ion the buyer will receive and remaining budget if exist * when he/she buys primordial ion * @param _budget The amount of ETH sent by buyer * @param _withETH Whether or not buyer is paying with ETH * @return uint256 of the amount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateAmountAndRemainderBudget(uint256 _budget, bool _withETH) internal view returns (uint256, uint256, bool) { // Calculate the amount of ion uint256 amount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial ion to be purchased uint256 remainderEth = _budget.sub(amount.mul(primordialBuyPrice)); uint256 _availableETH = availableETH(); // If paying with ETH, it can't exceed availableETH if (_withETH && _budget > availableETH()) { // Calculate the amount of ions amount = _availableETH.div(primordialBuyPrice); remainderEth = _budget.sub(amount.mul(primordialBuyPrice)); } // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(amount) >= TOTAL_PRIMORDIAL_FOR_SALE) { amount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = _budget.sub(amount.mul(primordialBuyPrice)); } return (amount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial ion to buyer and reward AO devs accordingly * @param amount The amount of primordial ion to be sent to buyer * @param to The recipient of ion * @return the lot Id of the buyer */ function _sendPrimordialAndRewardDev(uint256 amount, address to) internal returns (bytes32) { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkBonusPercentage, uint256 networkBonusAmount) = calculateMultiplierAndBonus(amount); primordialTotalBought = primordialTotalBought.add(amount); bytes32 _lotId = _createPrimordialLot(to, amount, multiplier, networkBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network ion Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkBonusAmount = (startingNetworkBonusMultiplier.sub(networkBonusPercentage).add(endingNetworkBonusMultiplier)).mul(amount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2)); } _mint(theAO, theAONetworkBonusAmount); return _lotId; } /** * @dev Create a lot with `primordialAmount` of primordial ions with `_multiplier` for an `account` * during network exchange, and reward `_networkBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialAmount The amount of primordial ions to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkBonusAmount The network ion bonus amount * @return Created lot Id */ function _createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) internal returns (bytes32) { bytes32 lotId = _aoIonLot.createPrimordialLot(_account, _primordialAmount, _multiplier, _networkBonusAmount); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], _multiplier, _primordialAmount); // If this is the first lot, set this as the max multiplier of the account if (_aoIonLot.totalLotsByAddress(_account) == 1) { ownerMaxMultiplier[_account] = _multiplier; } _mintPrimordial(_account, _primordialAmount); _mint(_account, _networkBonusAmount); return lotId; } /** * @dev Create `mintedAmount` Primordial ions and send it to `target` * @param target Address to receive the Primordial ions * @param mintedAmount The amount of Primordial ions it will receive */ function _mintPrimordial(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(address(0), address(this), mintedAmount); emit PrimordialTransfer(address(this), target, mintedAmount); } /** * @dev Create a lot with `amount` of ions at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _amount The amount of ions * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_amount > 0); bytes32 lotId = _aoIonLot.createWeightedMultiplierLot(_account, _amount, _weightedMultiplier); // If this is the first lot, set this as the max multiplier of the account if (_aoIonLot.totalLotsByAddress(_account) == 1) { ownerMaxMultiplier[_account] = _weightedMultiplier; } return lotId; } /** * @dev Create Lot and send `_value` Primordial ions from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function _createLotAndTransferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); (, address _lotOwner,,) = _aoIonLot.lotById(_createdLotId); // Make sure the new lot is created successfully require (_lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial ions require (_transferPrimordial(_from, _to, _value)); return true; } /** * @dev Send `_value` Primordial ions from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial ion * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial ion * @return startingNetworkBonusMultiplier The starting multiplier used to calculate network ion bonus * @return endingNetworkBonusMultiplier The ending multiplier used to calculate network ion bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkBonusMultiplier'); (uint256 endingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier); } } /** * @title AOPool * * This contract acts as the exchange between AO and ETH/ERC-20 compatible tokens */ contract AOPool is TheAO { using SafeMath for uint256; address public aoIonAddress; AOIon internal _aoIon; struct Pool { uint256 price; // Flat price of AO /** * If true, Pool is live and can be sold into. * Otherwise, Pool cannot be sold into. */ bool status; /** * If true, has sell cap. Otherwise, no sell cap. */ bool sellCapStatus; /** * Denominated in AO, creates a cap for the amount of AO that can be * put up for sale in this pool at `price` */ uint256 sellCapAmount; /** * If true, has quantity cap. Otherwise, no quantity cap. */ bool quantityCapStatus; /** * Denominated in AO, creates a cap for the amount of AO at any given time * that can be available for sale in this pool */ uint256 quantityCapAmount; /** * If true, the Pool is priced in an ERC20 compatible token. * Otherwise, the Pool is priced in Ethereum */ bool erc20CounterAsset; address erc20TokenAddress; // The address of the ERC20 Token /** * Used if ERC20 token needs to deviate from Ethereum in multiplication/division */ uint256 erc20TokenMultiplier; address adminAddress; // defaults to TheAO address, but can be modified } struct Lot { bytes32 lotId; // The ID of this Lot address seller; // Ethereum address of the seller uint256 lotQuantity; // Amount of AO being added to the Pool from this Lot uint256 poolId; // Identifier for the Pool this Lot is adding to uint256 poolPreSellSnapshot; // Amount of contributed to the Pool prior to this Lot Number uint256 poolSellLotSnapshot; // poolPreSellSnapshot + lotQuantity uint256 lotValueInCounterAsset; // Amount of AO x Pool Price uint256 counterAssetWithdrawn; // Amount of Counter-Asset withdrawn from this Lot uint256 ionWithdrawn; // Amount of AO withdrawn from this Lot uint256 timestamp; } // Contract variables uint256 public totalPool; uint256 public contractTotalLot; // Total lot from all pools uint256 public contractTotalSell; // Quantity of AO that has been contributed to all Pools uint256 public contractTotalBuy; // Quantity of AO that has been bought from all Pools uint256 public contractTotalQuantity; // Quantity of AO available to buy from all Pools uint256 public contractTotalWithdrawn; // Quantity of AO that has been withdrawn from all Pools uint256 public contractEthereumBalance; // Total Ethereum in contract uint256 public contractTotalEthereumWithdrawn; // Total Ethereum withdrawn from selling AO in contract // Mapping from Pool ID to Pool mapping (uint256 => Pool) public pools; // Mapping from Lot ID to Lot mapping (bytes32 => Lot) public lots; // Mapping from Pool ID to total Lots in the Pool mapping (uint256 => uint256) public poolTotalLot; // Mapping from Pool ID to quantity of AO available to buy at `price` mapping (uint256 => uint256) public poolTotalQuantity; // Mapping from Pool ID to quantity of AO that has been contributed to the Pool mapping (uint256 => uint256) public poolTotalSell; // Mapping from Pool ID to quantity of AO that has been bought from the Pool mapping (uint256 => uint256) public poolTotalBuy; // Mapping from Pool ID to quantity of AO that has been withdrawn from the Pool mapping (uint256 => uint256) public poolTotalWithdrawn; // Mapping from Pool ID to total Ethereum available to withdraw mapping (uint256 => uint256) public poolEthereumBalance; // Mapping from Pool ID to quantity of ERC20 token available to withdraw mapping (uint256 => uint256) public poolERC20TokenBalance; // Mapping from Pool ID to amount of Ethereum withdrawn from selling AO mapping (uint256 => uint256) public poolTotalEthereumWithdrawn; // Mapping from an address to quantity of AO put on sale from all sell lots mapping (address => uint256) public totalPutOnSale; // Mapping from an address to quantity of AO sold and redeemed from all sell lots mapping (address => uint256) public totalSold; // Mapping from an address to quantity of AO bought from all pool mapping (address => uint256) public totalBought; // Mapping from an address to amount of Ethereum withdrawn from selling AO mapping (address => uint256) public totalEthereumWithdrawn; // Mapping from an address to its Lots mapping (address => bytes32[]) internal ownerLots; // Mapping from Pool's Lot ID to Lot internal ID mapping (uint256 => mapping (bytes32 => uint256)) internal poolLotInternalIdLookup; // Mapping from Pool's Lot internal ID to total ion withdrawn mapping (uint256 => mapping (uint256 => uint256)) internal poolLotIonWithdrawn; // Mapping from Pool's tenth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolTenthLotIonWithdrawnSnapshot; // Mapping from Pool's hundredth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredthLotIonWithdrawnSnapshot; // Mapping from Pool's thousandth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolThousandthLotIonWithdrawnSnapshot; // Mapping from Pool's ten thousandth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolTenThousandthLotIonWithdrawnSnapshot; // Mapping from Pool's hundred thousandth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredThousandthLotIonWithdrawnSnapshot; // Mapping from Pool's millionth Lot to total ion withdrawn // This is to help optimize calculating the total ion withdrawn before certain Lot mapping (uint256 => mapping (uint256 => uint256)) internal poolMillionthLotIonWithdrawnSnapshot; // Event to be broadcasted to public when Pool is created event CreatePool(uint256 indexed poolId, address indexed adminAddress, uint256 price, bool status, bool sellCapStatus, uint256 sellCapAmount, bool quantityCapStatus, uint256 quantityCapAmount, bool erc20CounterAsset, address erc20TokenAddress, uint256 erc20TokenMultiplier); // Event to be broadcasted to public when Pool's status is updated // If status == true, start Pool // Otherwise, stop Pool event UpdatePoolStatus(uint256 indexed poolId, bool status); // Event to be broadcasted to public when Pool's admin address is changed event ChangeAdminAddress(uint256 indexed poolId, address newAdminAddress); /** * Event to be broadcasted to public when a seller sells AO * * If erc20CounterAsset is true, the Lot is priced in an ERC20 compatible token. * Otherwise, the Lot is priced in Ethereum */ event LotCreation(uint256 indexed poolId, bytes32 indexed lotId, address indexed seller, uint256 lotQuantity, uint256 price, uint256 poolPreSellSnapshot, uint256 poolSellLotSnapshot, uint256 lotValueInCounterAsset, bool erc20CounterAsset, uint256 timestamp); // Event to be broadcasted to public when a buyer buys AO event BuyWithEth(uint256 indexed poolId, address indexed buyer, uint256 buyQuantity, uint256 price, uint256 currentPoolTotalBuy); // Event to be broadcasted to public when a buyer withdraw ETH from Lot event WithdrawEth(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentLotValueInCounterAsset, uint256 currentLotCounterAssetWithdrawn); // Event to be broadcasted to public when a seller withdraw ion from Lot event WithdrawIon(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentlotValueInCounterAsset, uint256 currentLotIonWithdrawn); /** * @dev Constructor function */ constructor(address _aoIonAddress, address _nameTAOPositionAddress) public { setAOIonAddress(_aoIonAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** THE AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the AOIonAddress Address * @param _aoIonAddress The address of AOIonAddress */ function setAOIonAddress(address _aoIonAddress) public onlyTheAO { require (_aoIonAddress != address(0)); aoIonAddress = _aoIonAddress; _aoIon = AOIon(_aoIonAddress); } /** * @dev The AO sets NameTAOPosition address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO { _recipient.transfer(_amount); } /** * @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); require (_erc20.transfer(_recipient, _amount)); } /** * @dev TheAO creates a Pool * @param _price The flat price of AO * @param _status The status of the Pool * true = Pool is live and can be sold into * false = Pool cannot be sold into * @param _sellCapStatus Whether or not the Pool has sell cap * true = has sell cap * false = no sell cap * @param _sellCapAmount Cap for the amount of AO that can be put up for sale in this Pool at `_price` * @param _quantityCapStatus Whether or not the Pool has quantity cap * true = has quantity cap * false = no quantity cap * @param _quantityCapAmount Cap for the amount of AO at any given time that can be available for sale in this Pool * @param _erc20CounterAsset Type of the Counter-Asset * true = Pool is priced in ERC20 compatible Token * false = Pool is priced in Ethereum * @param _erc20TokenAddress The address of the ERC20 Token * @param _erc20TokenMultiplier Used if ERC20 Token needs to deviate from Ethereum in multiplication/division */ function createPool( uint256 _price, bool _status, bool _sellCapStatus, uint256 _sellCapAmount, bool _quantityCapStatus, uint256 _quantityCapAmount, bool _erc20CounterAsset, address _erc20TokenAddress, uint256 _erc20TokenMultiplier) public onlyTheAO { require (_price > 0); // Make sure sell cap amount is provided if sell cap is enabled if (_sellCapStatus == true) { require (_sellCapAmount > 0); } // Make sure quantity cap amount is provided if quantity cap is enabled if (_quantityCapStatus == true) { require (_quantityCapAmount > 0); } // Make sure the ERC20 token address and multiplier are provided // if this Pool is priced in ERC20 compatible Token if (_erc20CounterAsset == true) { require (AOLibrary.isValidERC20TokenAddress(_erc20TokenAddress)); require (_erc20TokenMultiplier > 0); } totalPool++; Pool storage _pool = pools[totalPool]; _pool.price = _price; _pool.status = _status; _pool.sellCapStatus = _sellCapStatus; if (_sellCapStatus) { _pool.sellCapAmount = _sellCapAmount; } _pool.quantityCapStatus = _quantityCapStatus; if (_quantityCapStatus) { _pool.quantityCapAmount = _quantityCapAmount; } _pool.erc20CounterAsset = _erc20CounterAsset; if (_erc20CounterAsset) { _pool.erc20TokenAddress = _erc20TokenAddress; _pool.erc20TokenMultiplier = _erc20TokenMultiplier; } _pool.adminAddress = msg.sender; emit CreatePool(totalPool, _pool.adminAddress, _pool.price, _pool.status, _pool.sellCapStatus, _pool.sellCapAmount, _pool.quantityCapStatus, _pool.quantityCapAmount, _pool.erc20CounterAsset, _pool.erc20TokenAddress, _pool.erc20TokenMultiplier); } /***** Pool's Admin Only Methods *****/ /** * @dev Start/Stop a Pool * @param _poolId The ID of the Pool * @param _status The status to set. true = start. false = stop */ function updatePoolStatus(uint256 _poolId, bool _status) public { // Check pool existence by requiring price > 0 require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress))); pools[_poolId].status = _status; emit UpdatePoolStatus(_poolId, _status); } /** * @dev Change Admin Address * @param _poolId The ID of the Pool * @param _adminAddress The new admin address to set */ function changeAdminAddress(uint256 _poolId, address _adminAddress) public { // Check pool existence by requiring price > 0 require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress))); require (_adminAddress != address(0)); pools[_poolId].adminAddress = _adminAddress; emit ChangeAdminAddress(_poolId, _adminAddress); } /***** Public Methods *****/ /** * @dev Seller sells AO in Pool `_poolId` - create a Lot to be added to a Pool for a seller. * @param _poolId The ID of the Pool * @param _quantity The amount of AO to be sold * @param _price The price supplied by seller */ function sell(uint256 _poolId, uint256 _quantity, uint256 _price) public { Pool memory _pool = pools[_poolId]; require (_pool.status == true && _pool.price == _price && _quantity > 0 && _aoIon.balanceOf(msg.sender) >= _quantity); // If there is a sell cap if (_pool.sellCapStatus == true) { require (poolTotalSell[_poolId].add(_quantity) <= _pool.sellCapAmount); } // If there is a quantity cap if (_pool.quantityCapStatus == true) { require (poolTotalQuantity[_poolId].add(_quantity) <= _pool.quantityCapAmount); } // Create Lot for this sell transaction contractTotalLot++; poolTotalLot[_poolId]++; // Generate Lot ID bytes32 _lotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalLot)); Lot storage _lot = lots[_lotId]; _lot.lotId = _lotId; _lot.seller = msg.sender; _lot.lotQuantity = _quantity; _lot.poolId = _poolId; _lot.poolPreSellSnapshot = poolTotalSell[_poolId]; _lot.poolSellLotSnapshot = poolTotalSell[_poolId].add(_quantity); _lot.lotValueInCounterAsset = _quantity.mul(_pool.price); _lot.timestamp = now; poolLotInternalIdLookup[_poolId][_lotId] = poolTotalLot[_poolId]; ownerLots[msg.sender].push(_lotId); // Update contract variables poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].add(_quantity); poolTotalSell[_poolId] = poolTotalSell[_poolId].add(_quantity); totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].add(_quantity); contractTotalQuantity = contractTotalQuantity.add(_quantity); contractTotalSell = contractTotalSell.add(_quantity); require (_aoIon.whitelistTransferFrom(msg.sender, address(this), _quantity)); emit LotCreation(_lot.poolId, _lot.lotId, _lot.seller, _lot.lotQuantity, _pool.price, _lot.poolPreSellSnapshot, _lot.poolSellLotSnapshot, _lot.lotValueInCounterAsset, _pool.erc20CounterAsset, _lot.timestamp); } /** * @dev Retrieve number of Lots an `_account` has * @param _account The address of the Lot's owner * @return Total Lots the owner has */ function ownerTotalLot(address _account) public view returns (uint256) { return ownerLots[_account].length; } /** * @dev Get list of owner's Lot IDs from `_from` to `_to` index * @param _account The address of the Lot's owner * @param _from The starting index, (i.e 0) * @param _to The ending index, (i.e total - 1) * @return list of owner's Lot IDs */ function ownerLotIds(address _account, uint256 _from, uint256 _to) public view returns (bytes32[] memory) { require (_from >= 0 && _to >= _from && ownerLots[_account].length > _to); bytes32[] memory _lotIds = new bytes32[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _lotIds[i.sub(_from)] = ownerLots[_account][i]; } return _lotIds; } /** * @dev Buyer buys AO from Pool `_poolId` with Ethereum * @param _poolId The ID of the Pool * @param _quantity The amount of AO to be bought * @param _price The price supplied by buyer */ function buyWithEth(uint256 _poolId, uint256 _quantity, uint256 _price) public payable { Pool memory _pool = pools[_poolId]; require (_pool.status == true && _pool.price == _price && _pool.erc20CounterAsset == false); require (_quantity > 0 && _quantity <= poolTotalQuantity[_poolId]); require (msg.value > 0 && msg.value.div(_pool.price) == _quantity); // Update contract variables poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].sub(_quantity); poolTotalBuy[_poolId] = poolTotalBuy[_poolId].add(_quantity); poolEthereumBalance[_poolId] = poolEthereumBalance[_poolId].add(msg.value); contractTotalQuantity = contractTotalQuantity.sub(_quantity); contractTotalBuy = contractTotalBuy.add(_quantity); contractEthereumBalance = contractEthereumBalance.add(msg.value); totalBought[msg.sender] = totalBought[msg.sender].add(_quantity); require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity)); emit BuyWithEth(_poolId, msg.sender, _quantity, _price, poolTotalBuy[_poolId]); } /** * @dev Seller withdraw Ethereum from Lot `_lotId` * @param _lotId The ID of the Lot */ function withdrawEth(bytes32 _lotId) public { Lot storage _lot = lots[_lotId]; require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0); (uint256 soldQuantity, uint256 ethAvailableToWithdraw,) = lotEthAvailableToWithdraw(_lotId); require (ethAvailableToWithdraw > 0 && ethAvailableToWithdraw <= _lot.lotValueInCounterAsset && ethAvailableToWithdraw <= poolEthereumBalance[_lot.poolId] && ethAvailableToWithdraw <= contractEthereumBalance && soldQuantity <= _lot.lotQuantity.sub(_lot.ionWithdrawn)); // Update lot variables _lot.counterAssetWithdrawn = _lot.counterAssetWithdrawn.add(ethAvailableToWithdraw); _lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(ethAvailableToWithdraw); // Update contract variables poolEthereumBalance[_lot.poolId] = poolEthereumBalance[_lot.poolId].sub(ethAvailableToWithdraw); poolTotalEthereumWithdrawn[_lot.poolId] = poolTotalEthereumWithdrawn[_lot.poolId].add(ethAvailableToWithdraw); contractEthereumBalance = contractEthereumBalance.sub(ethAvailableToWithdraw); contractTotalEthereumWithdrawn = contractTotalEthereumWithdrawn.add(ethAvailableToWithdraw); totalSold[msg.sender] = totalSold[msg.sender].add(soldQuantity); totalEthereumWithdrawn[msg.sender] = totalEthereumWithdrawn[msg.sender].add(ethAvailableToWithdraw); // Send eth to seller address(uint160(_lot.seller)).transfer(ethAvailableToWithdraw); //_lot.seller.transfer(ethAvailableToWithdraw); emit WithdrawEth(_lot.seller, _lot.lotId, _lot.poolId, ethAvailableToWithdraw, _lot.lotValueInCounterAsset, _lot.counterAssetWithdrawn); } /** * @dev Seller gets Lot `_lotId` (priced in ETH) available to withdraw info * @param _lotId The ID of the Lot * @return The amount of ion sold * @return Ethereum available to withdraw from the Lot * @return Current Ethereum withdrawn from the Lot */ function lotEthAvailableToWithdraw(bytes32 _lotId) public view returns (uint256, uint256, uint256) { Lot memory _lot = lots[_lotId]; require (_lot.seller != address(0)); Pool memory _pool = pools[_lot.poolId]; require (_pool.erc20CounterAsset == false); uint256 soldQuantity = 0; uint256 ethAvailableToWithdraw = 0; // Check whether or not there are ions withdrawn from Lots before this Lot uint256 lotAdjustment = totalIonWithdrawnBeforeLot(_lotId); if (poolTotalBuy[_lot.poolId] > _lot.poolPreSellSnapshot.sub(lotAdjustment) && _lot.lotValueInCounterAsset > 0) { soldQuantity = (poolTotalBuy[_lot.poolId] >= _lot.poolSellLotSnapshot.sub(lotAdjustment)) ? _lot.lotQuantity : poolTotalBuy[_lot.poolId].sub(_lot.poolPreSellSnapshot.sub(lotAdjustment)); if (soldQuantity > 0) { if (soldQuantity > _lot.ionWithdrawn) { soldQuantity = soldQuantity.sub(_lot.ionWithdrawn); } soldQuantity = soldQuantity.sub(_lot.counterAssetWithdrawn.div(_pool.price)); ethAvailableToWithdraw = soldQuantity.mul(_pool.price); assert (soldQuantity <= _lot.lotValueInCounterAsset.div(_pool.price)); assert (soldQuantity.add(_lot.ionWithdrawn) <= _lot.lotQuantity); assert (ethAvailableToWithdraw <= _lot.lotValueInCounterAsset); } } return (soldQuantity, ethAvailableToWithdraw, _lot.counterAssetWithdrawn); } /** * @dev Seller withdraw ion from Lot `_lotId` * @param _lotId The ID of the Lot * @param _quantity The amount of ion to withdraw */ function withdrawIon(bytes32 _lotId, uint256 _quantity) public { Lot storage _lot = lots[_lotId]; require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0); Pool memory _pool = pools[_lot.poolId]; require (_quantity > 0 && _quantity <= _lot.lotValueInCounterAsset.div(_pool.price)); // Update lot variables _lot.ionWithdrawn = _lot.ionWithdrawn.add(_quantity); _lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(_quantity.mul(_pool.price)); poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]] = poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]].add(_quantity); // Store Pool's millionth Lot snapshot uint256 millionth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000000); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(millionth.mul(1000000)) != 0) { millionth++; } poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth] = poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth].add(_quantity); // Store Pool's hundred thousandth Lot snapshot uint256 hundredThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100000); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredThousandth.mul(100000)) != 0) { hundredThousandth++; } poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth] = poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth].add(_quantity); // Store Pool's ten thousandth Lot snapshot uint256 tenThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10000); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenThousandth.mul(10000)) != 0) { tenThousandth++; } poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth] = poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth].add(_quantity); // Store Pool's thousandth Lot snapshot uint256 thousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(thousandth.mul(1000)) != 0) { thousandth++; } poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth] = poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth].add(_quantity); // Store Pool's hundredth Lot snapshot uint256 hundredth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredth.mul(100)) != 0) { hundredth++; } poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth] = poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth].add(_quantity); // Store Pool's tenth Lot snapshot uint256 tenth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10); if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenth.mul(10)) != 0) { tenth++; } poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth] = poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth].add(_quantity); // Update contract variables poolTotalQuantity[_lot.poolId] = poolTotalQuantity[_lot.poolId].sub(_quantity); contractTotalQuantity = contractTotalQuantity.sub(_quantity); poolTotalWithdrawn[_lot.poolId] = poolTotalWithdrawn[_lot.poolId].add(_quantity); contractTotalWithdrawn = contractTotalWithdrawn.add(_quantity); totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].sub(_quantity); assert (_lot.ionWithdrawn.add(_lot.lotValueInCounterAsset.div(_pool.price)).add(_lot.counterAssetWithdrawn.div(_pool.price)) == _lot.lotQuantity); require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity)); emit WithdrawIon(_lot.seller, _lot.lotId, _lot.poolId, _quantity, _lot.lotValueInCounterAsset, _lot.ionWithdrawn); } /** * @dev Get total ion withdrawn from all Lots before Lot `_lotId` * @param _lotId The ID of the Lot * @return Total ion withdrawn from all Lots before Lot `_lotId` */ function totalIonWithdrawnBeforeLot(bytes32 _lotId) public view returns (uint256) { Lot memory _lot = lots[_lotId]; require (_lot.seller != address(0) && poolLotInternalIdLookup[_lot.poolId][_lotId] > 0); uint256 totalIonWithdrawn = 0; uint256 lotInternalId = poolLotInternalIdLookup[_lot.poolId][_lotId]; uint256 lowerBound = 0; uint256 millionth = lotInternalId.div(1000000); if (millionth > 0) { for (uint256 i=1; i<=millionth; i++) { if (poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = millionth.mul(1000000); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } else { lowerBound = lowerBound.div(100000); } } uint256 hundredThousandth = lotInternalId.div(100000); if (hundredThousandth > 0) { for (uint256 i=lowerBound.add(1); i<=hundredThousandth; i++) { if (poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = hundredThousandth.mul(100000); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } else { lowerBound = lowerBound.div(10000); } } uint256 tenThousandth = lotInternalId.div(10000); if (tenThousandth > 0) { for (uint256 i=lowerBound.add(1); i<=tenThousandth; i++) { if (poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = tenThousandth.mul(10000); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } else { lowerBound = lowerBound.div(1000); } } uint256 thousandth = lotInternalId.div(1000); if (thousandth > 0) { for (uint256 i=lowerBound.add(1); i<=thousandth; i++) { if (poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = thousandth.mul(1000); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } else { lowerBound = lowerBound.div(100); } } uint256 hundredth = lotInternalId.div(100); if (hundredth > 0) { for (uint256 i=lowerBound.add(1); i<=hundredth; i++) { if (poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = hundredth.mul(100); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } else { lowerBound = lowerBound.div(10); } } uint256 tenth = lotInternalId.div(10); if (tenth > 0) { for (uint256 i=lowerBound.add(1); i<=tenth; i++) { if (poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i]); } } lowerBound = tenth.mul(10); if (lowerBound == lotInternalId) { totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]); return totalIonWithdrawn; } } for (uint256 i=lowerBound.add(1); i<lotInternalId; i++) { if (poolLotIonWithdrawn[_lot.poolId][i] > 0) { totalIonWithdrawn = totalIonWithdrawn.add(poolLotIonWithdrawn[_lot.poolId][i]); } } return totalIonWithdrawn; } }
Pool's Admin Only Methods / Start/Stop a Pool _poolId The ID of the Pool _status The status to set. true = start. false = stop/ Check pool existence by requiring price > 0
function updatePoolStatus(uint256 _poolId, bool _status) public { require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress))); pools[_poolId].status = _status; emit UpdatePoolStatus(_poolId, _status); }
985,736
./full_match/1/0x49c29feb858eae45FeE9866Ec0Dd5f0326E998C5/sources/contracts/Quick721.sol
Mint a single nft/
function safeMint(address to, uint256 tokenId) external { _safeMint(to, tokenId); }
9,712,529
// SPDX-License-Identifier: UNLICENSED /** โˆฉ~~~~โˆฉ ฮพ ๏ฝฅร—๏ฝฅ ฮพ ฮพใ€€~ใ€€ฮพ ฮพใ€€ใ€€ ฮพ ฮพใ€€ใ€€ โ€œ~๏ฝž~๏ฝžใ€‡ ฮพใ€€ใ€€ใ€€ใ€€ใ€€ใ€€ ฮพ ฮพ ฮพ ฮพ~๏ฝž~ฮพ ฮพ ฮพ ใ€€ ฮพ_ฮพฮพ_ฮพใ€€ฮพ_ฮพฮพ_ฮพ Alpaca Fin Corporation */ pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "../Vault.sol"; contract Actions { /// @dev The next position ID to be assigned. uint256 public nextPositionID; /// @dev Mapping of vault => vault's position ID => surrogate key mapping(address => mapping(uint256 => uint256)) public surrogateOf; /// @dev Mapping of vault => vault's positionId => owner mapping(address => mapping(uint256 => address)) public ownerOf; constructor() public { nextPositionID = 1; } uint8 private constant ACTION_NEW_SURROGATE = 1; uint8 private constant ACTION_WORK = 2; function _doNewSurrogate() internal returns (uint256) { return nextPositionID++; } function _doWork( bytes memory _data, uint256 _msgValue, uint256 _surrogateID ) internal { // 1. Decode data ( address payable _vault, uint256 _posId, address _worker, uint256 _principalAmount, uint256 _borrowAmount, uint256 _maxReturn, bytes memory _workData ) = abi.decode(_data, (address, uint256, address, uint256, uint256, uint256, bytes)); // 2. Sanity check // - If new position, then set ownerOf to be msg.sender // - else check that msg.sender is the one who altering the position if (_posId == 0) { require(_surrogateID != 0, "bad surrogate"); uint256 _nextPositionID = Vault(_vault).nextPositionID(); ownerOf[_vault][_nextPositionID] = msg.sender; surrogateOf[_vault][_nextPositionID] = _surrogateID; } else require(ownerOf[_vault][_posId] == msg.sender, "!owner"); // 3. Call work to altering Vault position Vault(_vault).work{ value: _msgValue }(_posId, _worker, _principalAmount, _borrowAmount, _maxReturn, _workData); } function execute( uint8[] calldata _actions, uint256[] calldata _msgValues, bytes[] calldata _datas ) external payable { uint256 value; for (uint256 i = 0; i < _actions.length; i++) { uint8 _action = _actions[i]; if (_action == ACTION_NEW_SURROGATE) { value = _doNewSurrogate(); } if (_action == ACTION_WORK) { _doWork(_datas[i], _msgValues[i], value); } } } }
1. Decode data 2. Sanity check - If new position, then set ownerOf to be msg.sender - else check that msg.sender is the one who altering the position
function _doWork( bytes memory _data, uint256 _msgValue, uint256 _surrogateID ) internal { ( address payable _vault, uint256 _posId, address _worker, uint256 _principalAmount, uint256 _borrowAmount, uint256 _maxReturn, bytes memory _workData ) = abi.decode(_data, (address, uint256, address, uint256, uint256, uint256, bytes)); if (_posId == 0) { require(_surrogateID != 0, "bad surrogate"); uint256 _nextPositionID = Vault(_vault).nextPositionID(); ownerOf[_vault][_nextPositionID] = msg.sender; surrogateOf[_vault][_nextPositionID] = _surrogateID; } else require(ownerOf[_vault][_posId] == msg.sender, "!owner"); }
6,435,827
pragma solidity >=0.4.22 <0.6.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 { //------------------------------------------------------------------------- /// @dev Emits when owner address changes by any mechanism. //------------------------------------------------------------------------- event OwnershipTransfer (address previousOwner, address newOwner); // Wallet address that can sucessfully execute onlyOwner functions address owner; //------------------------------------------------------------------------- /// @dev Sets the owner of the contract to the sender account. //------------------------------------------------------------------------- constructor() public { owner = msg.sender; emit OwnershipTransfer(address(0), owner); } //------------------------------------------------------------------------- /// @dev Throws if called by any account other than `owner`. //------------------------------------------------------------------------- modifier onlyOwner() { require( msg.sender == owner, "Function can only be called by contract owner" ); _; } //------------------------------------------------------------------------- /// @notice Transfer control of the contract to a newOwner. /// @dev Throws if `_newOwner` is zero address. /// @param _newOwner The address to transfer ownership to. //------------------------------------------------------------------------- function transferOwnership(address _newOwner) public onlyOwner { // for safety, new owner parameter must not be 0 require ( _newOwner != address(0), "New owner address cannot be zero" ); // define local variable for old owner address oldOwner = owner; // set owner to new owner owner = _newOwner; // emit ownership transfer event emit OwnershipTransfer(oldOwner, _newOwner); } } interface VIP181 { function ownerOf(uint256 _tokenId) external view returns(address payable); function getApproved(uint256 _tokenId) external view returns(address); function isApprovedForAll(address _owner, address _operator) external view returns(bool); } interface VIP180 { function balanceOf(address _tokenOwner) external view returns(uint); function transfer(address _to, uint _tokens) external returns(bool); function transferFrom(address _from, address _to, uint _tokens) external returns(bool); } //----------------------------------------------------------------------------- /// @title AAC External Token Handler /// @notice Defines depositing and withdrawal of VET and VIP-180-compliant /// tokens into AACs. //----------------------------------------------------------------------------- contract AacExternalTokens is Ownable { //------------------------------------------------------------------------- /// @dev Emits when external tokens are deposited into AACs from a wallet. //------------------------------------------------------------------------- event DepositExternal( address indexed _from, uint indexed _to, address indexed _tokenContract, uint _tokens ); //------------------------------------------------------------------------- /// @dev Emits when external tokens are withdrawn from AACs to a wallet. //------------------------------------------------------------------------- event WithdrawExternal( uint indexed _from, address indexed _to, address indexed _tokenContract, uint _tokens ); //------------------------------------------------------------------------- /// @dev Emits when external tokens are tranferred from AACs to another AAC. //------------------------------------------------------------------------- event TransferExternal( uint indexed _from, uint indexed _to, address indexed _tokenContract, uint _tokens ); // AAC contract VIP181 public aacContract; // handles the balances of AACs for every VIP180 token address mapping (address => mapping(uint => uint)) externalTokenBalances; // enumerates the deposited VIP180 contract addresses address[] public trackedVip180s; // guarantees above array contains unique addresses mapping (address => bool) isTracking; uint constant UID_MAX = 0xFFFFFFFFFFFFFF; //------------------------------------------------------------------------- /// @dev Throws if called by any account other than token owner, approved /// address, or authorized operator. //------------------------------------------------------------------------- modifier canOperate(uint _uid) { // sender must be owner of AAC #uid, or sender must be the // approved address of AAC #uid, or an authorized operator for // AAC owner address owner = aacContract.ownerOf(_uid); require ( msg.sender == owner || msg.sender == aacContract.getApproved(_uid) || aacContract.isApprovedForAll(owner, msg.sender), "Not authorized to operate for this AAC" ); _; } //------------------------------------------------------------------------- /// @dev Throws if parameter is zero //------------------------------------------------------------------------- modifier notZero(uint _param) { require(_param != 0, "Parameter cannot be zero"); _; } function setAacContract(address _aacAddress) external onlyOwner { aacContract = VIP181(_aacAddress); } //------------------------------------------------------------------------- /// @notice Deposit VET from sender to approved AAC /// @dev Throws if VET to deposit is zero. Throws if sender is not /// approved to operate AAC #`toUid`. Throws if sender has insufficient /// balance for deposit. /// @param _toUid the AAC to deposit the VET into //------------------------------------------------------------------------- function depositVET(uint _toUid) external payable canOperate(_toUid) notZero(msg.value) { // add amount to AAC's balance externalTokenBalances[address(this)][_toUid] += msg.value; // emit event emit DepositExternal(msg.sender, _toUid, address(this), msg.value); } //------------------------------------------------------------------------- /// @notice Withdraw VET from approved AAC to AAC's owner /// @dev Throws if VET to withdraw is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC /// #`_fromUid` has insufficient balance to withdraw. /// @param _fromUid the AAC to withdraw the VET from /// @param _amount the amount of VET to withdraw (in Wei) //------------------------------------------------------------------------- function withdrawVET( uint _fromUid, uint _amount ) external canOperate(_fromUid) notZero(_amount) { // AAC must have sufficient VET balance require ( externalTokenBalances[address(this)][_fromUid] >= _amount, "Insufficient VET to withdraw" ); // subtract amount from AAC's balance externalTokenBalances[address(this)][_fromUid] -= _amount; address payable receiver = aacContract.ownerOf(_fromUid); // call transfer function receiver.transfer(_amount); // emit event emit WithdrawExternal(_fromUid, receiver, address(this), _amount); } //------------------------------------------------------------------------- /// @notice Withdraw VET from approved AAC and send to '_to' /// @dev Throws if VET to transfer is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC /// #`_fromUid` has insufficient balance to withdraw. /// @param _fromUid the AAC to withdraw and send the VET from /// @param _to the address to receive the transferred VET /// @param _amount the amount of VET to withdraw (in Wei) //------------------------------------------------------------------------- function transferVETToWallet( uint _fromUid, address payable _to, uint _amount ) external canOperate(_fromUid) notZero(_amount) { // AAC must have sufficient VET balance require ( externalTokenBalances[address(this)][_fromUid] >= _amount, "Insufficient VET to transfer" ); // subtract amount from AAC's balance externalTokenBalances[address(this)][_fromUid] -= _amount; // call transfer function _to.transfer(_amount); // emit event emit WithdrawExternal(_fromUid, _to, address(this), _amount); } //------------------------------------------------------------------------- /// @notice Transfer VET from your AAC to another AAC /// @dev Throws if tokens to transfer is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC #`_fromUid` has /// insufficient balance to transfer. Throws if receiver does not exist. /// @param _fromUid the AAC to withdraw the VIP-180 tokens from /// @param _toUid the identifier of the AAC to receive the VIP-180 tokens /// @param _amount the number of tokens to send //------------------------------------------------------------------------- function transferVETToAAC ( uint _fromUid, uint _toUid, uint _amount ) external canOperate(_fromUid) notZero(_amount) { // receiver must have an owner require(aacContract.ownerOf(_toUid) != address(0), "Invalid receiver UID"); // AAC must have sufficient token balance require ( externalTokenBalances[address(this)][_fromUid] >= _amount, "insufficient tokens to transfer" ); // subtract amount from sender's balance externalTokenBalances[address(this)][_fromUid] -= _amount; // add amount to receiver's balance externalTokenBalances[address(this)][_toUid] += _amount; // emit event emit TransferExternal(_fromUid, _toUid, address(this), _amount); } //------------------------------------------------------------------------- /// @notice Deposit VIP-180 tokens from sender to approved AAC /// @dev This contract address must be an authorized spender for sender. /// Throws if tokens to deposit is zero. Throws if sender is not an /// approved operator for AAC #`toUid`. Throws if this contract address /// has insufficient allowance for transfer. Throws if sender has /// insufficient balance for deposit. Throws if tokenAddress has no /// transferFrom function. /// @param _tokenAddress the VIP-180 contract address /// @param _toUid the AAC to deposit the VIP-180 tokens into /// @param _tokens the number of tokens to deposit //------------------------------------------------------------------------- function depositTokens ( address _tokenAddress, uint _toUid, uint _tokens ) external canOperate(_toUid) notZero(_tokens) { // add token contract address to list of tracked token addresses if (isTracking[_tokenAddress] == false) { trackedVip180s.push(_tokenAddress); isTracking[_tokenAddress] = true; } // initialize token contract VIP180 tokenContract = VIP180(_tokenAddress); // add amount to AAC's balance externalTokenBalances[_tokenAddress][_toUid] += _tokens; // call transferFrom function from token contract tokenContract.transferFrom(msg.sender, address(this), _tokens); // emit event emit DepositExternal(msg.sender, _toUid, _tokenAddress, _tokens); } //------------------------------------------------------------------------- /// @notice Deposit VIP-180 tokens from '_to' to approved AAC /// @dev This contract address must be an authorized spender for '_from'. /// Throws if tokens to deposit is zero. Throws if sender is not an /// approved operator for AAC #`toUid`. Throws if this contract address /// has insufficient allowance for transfer. Throws if sender has /// insufficient balance for deposit. Throws if tokenAddress has no /// transferFrom function. /// @param _tokenAddress the VIP-180 contract address /// @param _from the address sending VIP-180 tokens to deposit /// @param _toUid the AAC to deposit the VIP-180 tokens into /// @param _tokens the number of tokens to deposit //------------------------------------------------------------------------- function depositTokensFrom ( address _tokenAddress, address _from, uint _toUid, uint _tokens ) external canOperate(_toUid) notZero(_tokens) { // add token contract address to list of tracked token addresses if (isTracking[_tokenAddress] == false) { trackedVip180s.push(_tokenAddress); isTracking[_tokenAddress] = true; } // initialize token contract VIP180 tokenContract = VIP180(_tokenAddress); // add amount to AAC's balance externalTokenBalances[_tokenAddress][_toUid] += _tokens; // call transferFrom function from token contract tokenContract.transferFrom(_from, address(this), _tokens); // emit event emit DepositExternal(_from, _toUid, _tokenAddress, _tokens); } //------------------------------------------------------------------------- /// @notice Withdraw VIP-180 tokens from approved AAC to AAC's /// owner /// @dev Throws if tokens to withdraw is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC /// #`_fromUid` has insufficient balance to withdraw. Throws if /// tokenAddress has no transfer function. /// @param _tokenAddress the VIP-180 contract address /// @param _fromUid the AAC to withdraw the VIP-180 tokens from /// @param _tokens the number of tokens to withdraw //------------------------------------------------------------------------- function withdrawTokens ( address _tokenAddress, uint _fromUid, uint _tokens ) external canOperate(_fromUid) notZero(_tokens) { // AAC must have sufficient token balance require ( externalTokenBalances[_tokenAddress][_fromUid] >= _tokens, "insufficient tokens to withdraw" ); // initialize token contract VIP180 tokenContract = VIP180(_tokenAddress); // subtract amount from AAC's balance externalTokenBalances[_tokenAddress][_fromUid] -= _tokens; // call transfer function from token contract tokenContract.transfer(aacContract.ownerOf(_fromUid), _tokens); // emit event emit WithdrawExternal(_fromUid, msg.sender, _tokenAddress, _tokens); } //------------------------------------------------------------------------- /// @notice Transfer VIP-180 tokens from your AAC to `_to` /// @dev Throws if tokens to transfer is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC /// #`_fromUid` has insufficient balance to transfer. Throws if /// tokenAddress has no transfer function. /// @param _tokenAddress the VIP-180 contract address /// @param _fromUid the AAC to withdraw the VIP-180 tokens from /// @param _to the wallet address to receive the VIP-180 tokens /// @param _tokens the number of tokens to send //------------------------------------------------------------------------- function transferTokensToWallet ( address _tokenAddress, uint _fromUid, address _to, uint _tokens ) external canOperate(_fromUid) notZero(_tokens) { // AAC must have sufficient token balance require ( externalTokenBalances[_tokenAddress][_fromUid] >= _tokens, "insufficient tokens to transfer" ); // initialize token contract VIP180 tokenContract = VIP180(_tokenAddress); // subtract amount from AAC's balance externalTokenBalances[_tokenAddress][_fromUid] -= _tokens; // call transfer function from token contract tokenContract.transfer(_to, _tokens); // emit event emit WithdrawExternal(_fromUid, _to, _tokenAddress, _tokens); } //------------------------------------------------------------------------- /// @notice Transfer VIP-180 tokens from your AAC to another AAC /// @dev Throws if tokens to transfer is zero. Throws if sender is not an /// approved operator for AAC #`_fromUid`. Throws if AAC /// #`_fromUid` has insufficient balance to transfer. Throws if /// tokenAddress has no transfer function. Throws if receiver does not /// exist. /// @param _tokenAddress the VIP-180 contract address /// @param _fromUid the AAC to withdraw the VIP-180 tokens from /// @param _toUid the identifier of the AAC to receive the VIP-180 tokens /// @param _tokens the number of tokens to send //------------------------------------------------------------------------- function transferTokensToAAC ( address _tokenAddress, uint _fromUid, uint _toUid, uint _tokens ) external canOperate(_fromUid) notZero(_tokens) { // receiver must have an owner require(aacContract.ownerOf(_toUid) != address(0), "Invalid receiver UID"); // AAC must have sufficient token balance require ( externalTokenBalances[_tokenAddress][_fromUid] >= _tokens, "insufficient tokens to transfer" ); // subtract amount from sender's balance externalTokenBalances[_tokenAddress][_fromUid] -= _tokens; // add amount to receiver's balance externalTokenBalances[_tokenAddress][_toUid] += _tokens; // emit event emit TransferExternal(_fromUid, _toUid, _tokenAddress, _tokens); } //------------------------------------------------------------------------- /// @notice Transfer balances of external tokens to new uid. AAC contract /// only. /// @dev throws unless sent by AAC contract //------------------------------------------------------------------------- function onLink(uint _oldUid, uint _newUid) external { require (msg.sender == address(aacContract), "Unauthorized transaction"); require (_oldUid > UID_MAX && _newUid <= UID_MAX); address tokenAddress; for(uint i = 0; i < trackedVip180s.length; ++i) { tokenAddress = trackedVip180s[i]; externalTokenBalances[tokenAddress][_newUid] = externalTokenBalances[tokenAddress][_oldUid]; } externalTokenBalances[address(this)][_newUid] = externalTokenBalances[address(this)][_oldUid]; } //------------------------------------------------------------------------- /// @notice Get external token balance for tokens deposited into AAC /// #`_uid`. /// @dev To query VET, use THIS CONTRACT'S address as '_tokenAddress'. /// @param _uid Owner of the tokens to query /// @param _tokenAddress Token creator contract address //------------------------------------------------------------------------- function getExternalTokenBalance( uint _uid, address _tokenAddress ) external view returns (uint) { return externalTokenBalances[_tokenAddress][_uid]; } }
------------------------------------------------------------------------- Deposit VIP-180 tokens from '_to' to approved AAC This contract address must be an authorized spender for '_from'. Throws if tokens to deposit is zero. Throws if sender is not an approved operator for AAC `toUid`. Throws if this contract address has insufficient allowance for transfer. Throws if sender has insufficient balance for deposit. Throws if tokenAddress has no transferFrom function. _tokenAddress the VIP-180 contract address _from the address sending VIP-180 tokens to deposit _toUid the AAC to deposit the VIP-180 tokens into _tokens the number of tokens to deposit------------------------------------------------------------------------- add token contract address to list of tracked token addresses
function depositTokensFrom ( address _tokenAddress, address _from, uint _toUid, uint _tokens ) external canOperate(_toUid) notZero(_tokens) { if (isTracking[_tokenAddress] == false) { trackedVip180s.push(_tokenAddress); isTracking[_tokenAddress] = true; } }
6,383,976
pragma solidity 0.4.23; /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title Stoppable * @dev Base contract which allows children to implement final irreversible stop mechanism. */ contract Stoppable is Pausable { event Stop(); bool public stopped = false; /** * @dev Modifier to make a function callable only when the contract is not stopped. */ modifier whenNotStopped() { require(!stopped); _; } /** * @dev Modifier to make a function callable only when the contract is stopped. */ modifier whenStopped() { require(stopped); _; } /** * @dev called by the owner to pause, triggers stopped state */ function stop() public onlyOwner whenNotStopped { stopped = true; emit Stop(); } } /** * @title Eth2Phone Escrow Contract * @dev Contract allows to send ether through verifier (owner of contract). * * Only verifier can initiate withdrawal to recipient's address. * Verifier cannot choose recipient's address without * transit private key generated by sender. * * Sender is responsible to provide transit private key * to recipient off-chain. * * Recepient signs address to receive with transit private key and * provides signed address to verification server. * (See VerifyTransferSignature method for details.) * * Verifier verifies off-chain the recipient in accordance with verification * conditions (e.g., phone ownership via SMS authentication) and initiates * withdrawal to the address provided by recipient. * (See withdraw method for details.) * * Verifier charges commission for it's services. * * Sender is able to cancel transfer if it's not yet cancelled or withdrawn * by recipient. * (See cancelTransfer method for details.) */ contract e2pEscrow is Stoppable, SafeMath { // fixed amount of wei accrued to verifier with each transfer uint public commissionFee; // verifier can withdraw this amount from smart-contract uint public commissionToWithdraw; // in wei // verifier's address address public verifier; /* * EVENTS */ event LogDeposit( address indexed sender, address indexed transitAddress, uint amount, uint commission ); event LogCancel( address indexed sender, address indexed transitAddress ); event LogWithdraw( address indexed sender, address indexed transitAddress, address indexed recipient, uint amount ); event LogWithdrawCommission(uint commissionAmount); event LogChangeFixedCommissionFee( uint oldCommissionFee, uint newCommissionFee ); event LogChangeVerifier( address oldVerifier, address newVerifier ); struct Transfer { address from; uint amount; // in wei } // Mappings of transitAddress => Transfer Struct mapping (address => Transfer) transferDct; /** * @dev Contructor that sets msg.sender as owner (verifier) in Ownable * and sets verifier's fixed commission fee. * @param _commissionFee uint Verifier's fixed commission for each transfer */ constructor(uint _commissionFee, address _verifier) public { commissionFee = _commissionFee; verifier = _verifier; } modifier onlyVerifier() { require(msg.sender == verifier); _; } /** * @dev Deposit ether to smart-contract and create transfer. * Transit address is assigned to transfer by sender. * Recipient should sign withrawal address with the transit private key * * @param _transitAddress transit address assigned to transfer. * @return True if success. */ function deposit(address _transitAddress) public whenNotPaused whenNotStopped payable returns(bool) { // can not override existing transfer require(transferDct[_transitAddress].amount == 0); require(msg.value > commissionFee); // saving transfer details transferDct[_transitAddress] = Transfer( msg.sender, safeSub(msg.value, commissionFee)//amount = msg.value - comission ); // accrue verifier's commission commissionToWithdraw = safeAdd(commissionToWithdraw, commissionFee); // log deposit event emit LogDeposit(msg.sender, _transitAddress, msg.value, commissionFee); return true; } /** * @dev Change verifier's fixed commission fee. * Only owner can change commision fee. * * @param _newCommissionFee uint New verifier's fixed commission * @return True if success. */ function changeFixedCommissionFee(uint _newCommissionFee) public whenNotPaused whenNotStopped onlyOwner returns(bool success) { uint oldCommissionFee = commissionFee; commissionFee = _newCommissionFee; emit LogChangeFixedCommissionFee(oldCommissionFee, commissionFee); return true; } /** * @dev Change verifier's address. * Only owner can change verifier's address. * * @param _newVerifier address New verifier's address * @return True if success. */ function changeVerifier(address _newVerifier) public whenNotPaused whenNotStopped onlyOwner returns(bool success) { address oldVerifier = verifier; verifier = _newVerifier; emit LogChangeVerifier(oldVerifier, verifier); return true; } /** * @dev Transfer accrued commission to verifier's address. * @return True if success. */ function withdrawCommission() public whenNotPaused returns(bool success) { uint commissionToTransfer = commissionToWithdraw; commissionToWithdraw = 0; owner.transfer(commissionToTransfer); // owner is verifier emit LogWithdrawCommission(commissionToTransfer); return true; } /** * @dev Get transfer details. * @param _transitAddress transit address assigned to transfer * @return Transfer details (id, sender, amount) */ function getTransfer(address _transitAddress) public constant returns ( address id, address from, // transfer sender uint amount) // in wei { Transfer memory transfer = transferDct[_transitAddress]; return ( _transitAddress, transfer.from, transfer.amount ); } /** * @dev Cancel transfer and get sent ether back. Only transfer sender can * cancel transfer. * @param _transitAddress transit address assigned to transfer * @return True if success. */ function cancelTransfer(address _transitAddress) public returns (bool success) { Transfer memory transferOrder = transferDct[_transitAddress]; // only sender can cancel transfer; require(msg.sender == transferOrder.from); delete transferDct[_transitAddress]; // transfer ether to recipient's address msg.sender.transfer(transferOrder.amount); // log cancel event emit LogCancel(msg.sender, _transitAddress); return true; } /** * @dev Verify that address is signed with correct verification private key. * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if signature is correct. */ function verifySignature( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s) public pure returns(bool success) { bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", _recipient); address retAddr = ecrecover(prefixedHash, _v, _r, _s); return retAddr == _transitAddress; } /** * @dev Verify that address is signed with correct private key for * verification public key assigned to transfer. * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if signature is correct. */ function verifyTransferSignature( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s) public pure returns(bool success) { return (verifySignature(_transitAddress, _recipient, _v, _r, _s)); } /** * @dev Withdraw transfer to recipient's address if it is correctly signed * with private key for verification public key assigned to transfer. * * @param _transitAddress transit address assigned to transfer * @param _recipient address Signed address. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return True if success. */ function withdraw( address _transitAddress, address _recipient, uint8 _v, bytes32 _r, bytes32 _s ) public onlyVerifier // only through verifier can withdraw transfer; whenNotPaused whenNotStopped returns (bool success) { Transfer memory transferOrder = transferDct[_transitAddress]; // verifying signature (verifySignature(_transitAddress, _recipient, _v, _r, _s )); delete transferDct[_transitAddress]; // transfer ether to recipient's address _recipient.transfer(transferOrder.amount); // log withdraw event emit LogWithdraw(transferOrder.from, _transitAddress, _recipient, transferOrder.amount); return true; } // fallback function - do not receive ether by default function() public payable { revert(); } }
Deposit ether to smart-contract and create transfer. Transit address is assigned to transfer by sender. Recipient should sign withrawal address with the transit private key _transitAddress transit address assigned to transfer. return True if success./ can not override existing transfer saving transfer details accrue verifier's commission log deposit event
function deposit(address _transitAddress) public whenNotPaused whenNotStopped payable returns(bool) { require(transferDct[_transitAddress].amount == 0); require(msg.value > commissionFee); transferDct[_transitAddress] = Transfer( msg.sender, ); commissionToWithdraw = safeAdd(commissionToWithdraw, commissionFee); emit LogDeposit(msg.sender, _transitAddress, msg.value, commissionFee); return true; }
1,098,890
./partial_match/1/0xbb963750b4e02e044E9b91A68Ef1Fb0d35787654/sources/Pauseable.sol
Enable pause by setting {_paused} to true, then emit the related event
function pause() public virtual whenNotPaused() onlyOwner() { _paused = true; emit Paused(msg.sender); }
4,163,276
./full_match/11155111/0x9587EA65C1a544348dA0eF8B964ab0f0ee3579E7/sources/contracts/Contract.sol
utility to create a creator profile when new profile is created, profileId is returned todo implement displaying offering under profile create place for the newProfile inside createdProfiles state variable emit event return the index of the new profile
function createNewProfile(address _owner, string memory _email, string memory _username, string memory _firstname, string memory _lastname, string memory _profileDescription, string memory _profilePic, string memory _bannerPic) public returns (uint256) { Profile storage newProfile = createdProfiles.push(); newProfile.owner = _owner; newProfile.email = _email; newProfile.username = _username; newProfile.firstname = _firstname; newProfile.lastname = _lastname; newProfile.profileDescription = _profileDescription; newProfile.profilePic = _profilePic; newProfile.bannerPic = _bannerPic; emit NewProfileCreated( msg.sender, block.timestamp, _email ); return createdProfiles.length; }
3,814,068
/* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE โ€œTERMSโ€) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the โ€œPROTOCOLโ€) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMSย (โ€œDLPsโ€). PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS. IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL. Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age. License; No Warranties; Limitation of Liability; (a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause. (b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", โ€œWITH ALL FAULTSโ€ and โ€œAS AVAILABLEโ€ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. (c) 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. */ // File: contracts/bprotocol/interfaces/IComptroller.sol pragma solidity 0.5.16; interface IComptroller { // ComptrollerLensInterface.sol // ============================= function markets(address) external view returns (bool, uint); function oracle() external view returns (address); function getAccountLiquidity(address) external view returns (uint, uint, uint); function getAssetsIn(address) external view returns (address[] memory); function compAccrued(address) external view returns (uint); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external; // Public storage defined in Comptroller contract // =============================================== function checkMembership(address account, address cToken) external view returns (bool); function closeFactorMantissa() external returns (uint256); function liquidationIncentiveMantissa() external returns (uint256); // Public/external functions defined in Comptroller contract // ========================================================== function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function getAllMarkets() external view returns (address[] memory); function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint); function compBorrowState(address cToken) external returns (uint224, uint32); function compSupplyState(address cToken) external returns (uint224, uint32); } // File: contracts/bprotocol/interfaces/IRegistry.sol pragma solidity 0.5.16; interface IRegistry { // Ownable function transferOwnership(address newOwner) external; // Compound contracts function comp() external view returns (address); function comptroller() external view returns (address); function cEther() external view returns (address); // B.Protocol contracts function bComptroller() external view returns (address); function score() external view returns (address); function pool() external view returns (address); // Avatar functions function delegate(address avatar, address delegatee) external view returns (bool); function doesAvatarExist(address avatar) external view returns (bool); function doesAvatarExistFor(address owner) external view returns (bool); function ownerOf(address avatar) external view returns (address); function avatarOf(address owner) external view returns (address); function newAvatar() external returns (address); function getAvatar(address owner) external returns (address); // avatar whitelisted calls function whitelistedAvatarCalls(address target, bytes4 functionSig) external view returns(bool); function setPool(address newPool) external; function setWhitelistAvatarCall(address target, bytes4 functionSig, bool list) external; } // File: contracts/bprotocol/interfaces/IScore.sol pragma solidity 0.5.16; interface IScore { function updateDebtScore(address _user, address cToken, int256 amount) external; function updateCollScore(address _user, address cToken, int256 amount) external; function slashedScore(address _user, address cToken, int256 amount) external; } // File: contracts/bprotocol/lib/CarefulMath.sol pragma solidity 0.5.16; /** * @title Careful Math * @author Compound * @notice COPY TAKEN FROM COMPOUND FINANCE * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: contracts/bprotocol/lib/Exponential.sol pragma solidity 0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // New functions added by BProtocol // ================================= function mulTrucate(uint a, uint b) internal pure returns (uint) { return mul_(a, b) / expScale; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [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"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/bprotocol/interfaces/CTokenInterfaces.sol pragma solidity 0.5.16; contract CTokenInterface { /* ERC20 */ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /* User Interface */ function isCToken() external view returns (bool); function underlying() external view returns (IERC20); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } contract ICToken is CTokenInterface { /* User Interface */ function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); } // Workaround for issue https://github.com/ethereum/solidity/issues/526 // Defined separate contract as `mint()` override with `.value()` has issues contract ICErc20 is ICToken { function mint(uint mintAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); } contract ICEther is ICToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } contract IPriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CTokenInterface cToken) external view returns (uint); } // File: contracts/bprotocol/avatar/AbsAvatarBase.sol pragma solidity 0.5.16; contract AbsAvatarBase is Exponential { using SafeERC20 for IERC20; IRegistry public registry; bool public quit; /* Storage for topup details */ // Topped up cToken ICToken public toppedUpCToken; // Topped up amount of tokens uint256 public toppedUpAmount; // Remaining max amount available for liquidation uint256 public remainingLiquidationAmount; // Liquidation cToken ICToken public liquidationCToken; modifier onlyAvatarOwner() { _allowOnlyAvatarOwner(); _; } function _allowOnlyAvatarOwner() internal view { require(msg.sender == registry.ownerOf(address(this)), "sender-not-owner"); } modifier onlyPool() { _allowOnlyPool(); _; } function _allowOnlyPool() internal view { require(msg.sender == pool(), "only-pool-authorized"); } modifier onlyBComptroller() { _allowOnlyBComptroller(); _; } function _allowOnlyBComptroller() internal view { require(msg.sender == registry.bComptroller(), "only-BComptroller-authorized"); } modifier postPoolOp(bool debtIncrease) { _; _reevaluate(debtIncrease); } function _initAvatarBase(address _registry) internal { require(registry == IRegistry(0x0), "avatar-already-init"); registry = IRegistry(_registry); } /** * @dev Hard check to ensure untop is allowed and then reset remaining liquidation amount */ function _hardReevaluate() internal { // Check: must allowed untop require(canUntop(), "cannot-untop"); // Reset it to force re-calculation remainingLiquidationAmount = 0; } /** * @dev Soft check and reset remaining liquidation amount */ function _softReevaluate() private { if(isPartiallyLiquidated()) { _hardReevaluate(); } } function _reevaluate(bool debtIncrease) private { if(debtIncrease) { _hardReevaluate(); } else { _softReevaluate(); } } function _isCEther(ICToken cToken) internal view returns (bool) { return address(cToken) == registry.cEther(); } function _score() internal view returns (IScore) { return IScore(registry.score()); } function toInt256(uint256 value) internal pure returns (int256) { int256 result = int256(value); require(result >= 0, "conversion-fail"); return result; } function isPartiallyLiquidated() public view returns (bool) { return remainingLiquidationAmount > 0; } function isToppedUp() public view returns (bool) { return toppedUpAmount > 0; } /** * @dev Checks if this Avatar can untop the amount. * @return `true` if allowed to borrow, `false` otherwise. */ function canUntop() public returns (bool) { // When not topped up, just return true if(!isToppedUp()) return true; IComptroller comptroller = IComptroller(registry.comptroller()); bool result = comptroller.borrowAllowed(address(toppedUpCToken), address(this), toppedUpAmount) == 0; return result; } function pool() public view returns (address payable) { return address(uint160(registry.pool())); } /** * @dev Returns the status if this Avatar's debt can be liquidated * @return `true` when this Avatar can be liquidated, `false` otherwise */ function canLiquidate() public returns (bool) { bool result = isToppedUp() && (remainingLiquidationAmount > 0) || (!canUntop()); return result; } // function reduce contract size function _ensureUserNotQuitB() internal view { require(! quit, "user-quit-B"); } /** * @dev Topup this avatar by repaying borrowings with ETH */ function topup() external payable onlyPool { _ensureUserNotQuitB(); address cEtherAddr = registry.cEther(); // when already topped bool _isToppedUp = isToppedUp(); if(_isToppedUp) { require(address(toppedUpCToken) == cEtherAddr, "already-topped-other-cToken"); } // 2. Repay borrows from Pool to topup ICEther cEther = ICEther(cEtherAddr); cEther.repayBorrow.value(msg.value)(); // 3. Store Topped-up details if(! _isToppedUp) toppedUpCToken = cEther; toppedUpAmount = add_(toppedUpAmount, msg.value); } /** * @dev Topup the borrowed position of this Avatar by repaying borrows from the pool * @notice Only Pool contract allowed to call the topup. * @param cToken CToken address to use to RepayBorrows * @param topupAmount Amount of tokens to Topup */ function topup(ICErc20 cToken, uint256 topupAmount) external onlyPool { _ensureUserNotQuitB(); // when already topped bool _isToppedUp = isToppedUp(); if(_isToppedUp) { require(toppedUpCToken == cToken, "already-topped-other-cToken"); } // 1. Transfer funds from the Pool contract IERC20 underlying = cToken.underlying(); underlying.safeTransferFrom(pool(), address(this), topupAmount); underlying.safeApprove(address(cToken), topupAmount); // 2. Repay borrows from Pool to topup require(cToken.repayBorrow(topupAmount) == 0, "RepayBorrow-fail"); // 3. Store Topped-up details if(! _isToppedUp) toppedUpCToken = cToken; toppedUpAmount = add_(toppedUpAmount, topupAmount); } function untop(uint amount) external onlyPool { _untop(amount, amount); } /** * @dev Untop the borrowed position of this Avatar by borrowing from Compound and transferring * it to the pool. * @notice Only Pool contract allowed to call the untop. */ function _untop(uint amount, uint amountToBorrow) internal { // when already untopped if(!isToppedUp()) return; // 1. Udpdate storage for toppedUp details require(toppedUpAmount >= amount, "amount>=toppedUpAmount"); toppedUpAmount = sub_(toppedUpAmount, amount); if((toppedUpAmount == 0) && (remainingLiquidationAmount > 0)) remainingLiquidationAmount = 0; // 2. Borrow from Compound and send tokens to Pool if(amountToBorrow > 0 ) require(toppedUpCToken.borrow(amountToBorrow) == 0, "borrow-fail"); if(address(toppedUpCToken) == registry.cEther()) { // 3. Send borrowed ETH to Pool contract // Sending ETH to Pool using `.send()` to avoid DoS attack bool success = pool().send(amount); success; // shh: Not checking return value to avoid DoS attack } else { // 3. Transfer borrowed amount to Pool contract IERC20 underlying = toppedUpCToken.underlying(); underlying.safeTransfer(pool(), amount); } } function _untop() internal { // when already untopped if(!isToppedUp()) return; _untop(toppedUpAmount, toppedUpAmount); } function _untopBeforeRepay(ICToken cToken, uint256 repayAmount) internal returns (uint256 amtToRepayOnCompound) { if(toppedUpAmount > 0 && cToken == toppedUpCToken) { // consume debt from cushion first uint256 amtToUntopFromB = repayAmount >= toppedUpAmount ? toppedUpAmount : repayAmount; _untop(toppedUpAmount, sub_(toppedUpAmount, amtToUntopFromB)); amtToRepayOnCompound = sub_(repayAmount, amtToUntopFromB); } else { amtToRepayOnCompound = repayAmount; } } function _doLiquidateBorrow( ICToken debtCToken, uint256 underlyingAmtToLiquidate, uint256 amtToDeductFromTopup, ICToken collCToken ) internal onlyPool returns (uint256) { address payable poolContract = pool(); // 1. Is toppedUp OR partially liquidated bool partiallyLiquidated = isPartiallyLiquidated(); require(isToppedUp() || partiallyLiquidated, "cant-perform-liquidateBorrow"); if(partiallyLiquidated) { require(debtCToken == liquidationCToken, "debtCToken!=liquidationCToken"); } else { require(debtCToken == toppedUpCToken, "debtCToken!=toppedUpCToken"); liquidationCToken = debtCToken; } if(!partiallyLiquidated) { remainingLiquidationAmount = getMaxLiquidationAmount(debtCToken); } // 2. `underlayingAmtToLiquidate` is under limit require(underlyingAmtToLiquidate <= remainingLiquidationAmount, "amountToLiquidate-too-big"); // 3. Liquidator perform repayBorrow require(underlyingAmtToLiquidate >= amtToDeductFromTopup, "amtToDeductFromTopup>underlyingAmtToLiquidate"); uint256 amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup); if(amtToRepayOnCompound > 0) { bool isCEtherDebt = _isCEther(debtCToken); if(isCEtherDebt) { // CEther require(msg.value == amtToRepayOnCompound, "insuffecient-ETH-sent"); ICEther cEther = ICEther(registry.cEther()); cEther.repayBorrow.value(amtToRepayOnCompound)(); } else { // CErc20 // take tokens from pool contract IERC20 underlying = toppedUpCToken.underlying(); underlying.safeTransferFrom(poolContract, address(this), amtToRepayOnCompound); underlying.safeApprove(address(debtCToken), amtToRepayOnCompound); require(ICErc20(address(debtCToken)).repayBorrow(amtToRepayOnCompound) == 0, "repayBorrow-fail"); } } require(toppedUpAmount >= amtToDeductFromTopup, "amtToDeductFromTopup>toppedUpAmount"); toppedUpAmount = sub_(toppedUpAmount, amtToDeductFromTopup); // 4.1 Update remaining liquidation amount remainingLiquidationAmount = sub_(remainingLiquidationAmount, underlyingAmtToLiquidate); // 5. Calculate premium and transfer to Liquidator IComptroller comptroller = IComptroller(registry.comptroller()); (uint err, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(debtCToken), address(collCToken), underlyingAmtToLiquidate ); require(err == 0, "err-liquidateCalculateSeizeTokens"); // 6. Transfer permiumAmount to liquidator require(collCToken.transfer(poolContract, seizeTokens), "collCToken-xfr-fail"); return seizeTokens; } function getMaxLiquidationAmount(ICToken debtCToken) public returns (uint256) { if(isPartiallyLiquidated()) return remainingLiquidationAmount; uint256 avatarDebt = debtCToken.borrowBalanceCurrent(address(this)); // `toppedUpAmount` is also called poolDebt; uint256 totalDebt = add_(avatarDebt, toppedUpAmount); // When First time liquidation is performed after topup // maxLiquidationAmount = closeFactorMantissa * totalDedt / 1e18; IComptroller comptroller = IComptroller(registry.comptroller()); return mulTrucate(comptroller.closeFactorMantissa(), totalDebt); } function splitAmountToLiquidate( uint256 underlyingAmtToLiquidate, uint256 maxLiquidationAmount ) public view returns (uint256 amtToDeductFromTopup, uint256 amtToRepayOnCompound) { // underlyingAmtToLiqScalar = underlyingAmtToLiquidate * 1e18 (MathError mErr, Exp memory result) = mulScalar(Exp({mantissa: underlyingAmtToLiquidate}), expScale); require(mErr == MathError.NO_ERROR, "underlyingAmtToLiqScalar-fail"); uint underlyingAmtToLiqScalar = result.mantissa; // percent = underlyingAmtToLiqScalar / maxLiquidationAmount uint256 percentInScale = div_(underlyingAmtToLiqScalar, maxLiquidationAmount); // amtToDeductFromTopup = toppedUpAmount * percentInScale / 1e18 amtToDeductFromTopup = mulTrucate(toppedUpAmount, percentInScale); // amtToRepayOnCompound = underlyingAmtToLiquidate - amtToDeductFromTopup amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup); } /** * @dev Off-chain function to calculate `amtToDeductFromTopup` and `amtToRepayOnCompound` * @notice function is non-view but no-harm as CToken.borrowBalanceCurrent() only updates accured interest */ function calcAmountToLiquidate( ICToken debtCToken, uint256 underlyingAmtToLiquidate ) external returns (uint256 amtToDeductFromTopup, uint256 amtToRepayOnCompound) { uint256 amountToLiquidate = remainingLiquidationAmount; if(! isPartiallyLiquidated()) { amountToLiquidate = getMaxLiquidationAmount(debtCToken); } (amtToDeductFromTopup, amtToRepayOnCompound) = splitAmountToLiquidate(underlyingAmtToLiquidate, amountToLiquidate); } function quitB() external onlyAvatarOwner() { quit = true; _hardReevaluate(); } } // File: contracts/bprotocol/interfaces/IBToken.sol pragma solidity 0.5.16; interface IBToken { function cToken() external view returns (address); function borrowBalanceCurrent(address account) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); } // File: contracts/bprotocol/avatar/AbsComptroller.sol pragma solidity 0.5.16; /** * @title Abstract Comptroller contract for Avatar */ contract AbsComptroller is AbsAvatarBase { function enterMarket(address bToken) external onlyBComptroller returns (uint256) { address cToken = IBToken(bToken).cToken(); return _enterMarket(cToken); } function _enterMarket(address cToken) internal postPoolOp(false) returns (uint256) { address[] memory cTokens = new address[](1); cTokens[0] = cToken; return _enterMarkets(cTokens)[0]; } function enterMarkets(address[] calldata bTokens) external onlyBComptroller returns (uint256[] memory) { address[] memory cTokens = new address[](bTokens.length); for(uint256 i = 0; i < bTokens.length; i++) { cTokens[i] = IBToken(bTokens[i]).cToken(); } return _enterMarkets(cTokens); } function _enterMarkets(address[] memory cTokens) internal postPoolOp(false) returns (uint256[] memory) { IComptroller comptroller = IComptroller(registry.comptroller()); uint256[] memory result = comptroller.enterMarkets(cTokens); for(uint256 i = 0; i < result.length; i++) { require(result[i] == 0, "enter-markets-fail"); } return result; } function exitMarket(IBToken bToken) external onlyBComptroller postPoolOp(true) returns (uint256) { address cToken = bToken.cToken(); IComptroller comptroller = IComptroller(registry.comptroller()); uint result = comptroller.exitMarket(cToken); _disableCToken(cToken); return result; } function _disableCToken(address cToken) internal { ICToken(cToken).underlying().safeApprove(cToken, 0); } function claimComp() external onlyBComptroller { IComptroller comptroller = IComptroller(registry.comptroller()); comptroller.claimComp(address(this)); transferCOMP(); } function claimComp(address[] calldata bTokens) external onlyBComptroller { address[] memory cTokens = new address[](bTokens.length); for(uint256 i = 0; i < bTokens.length; i++) { cTokens[i] = IBToken(bTokens[i]).cToken(); } IComptroller comptroller = IComptroller(registry.comptroller()); comptroller.claimComp(address(this), cTokens); transferCOMP(); } function claimComp( address[] calldata bTokens, bool borrowers, bool suppliers ) external onlyBComptroller { address[] memory cTokens = new address[](bTokens.length); for(uint256 i = 0; i < bTokens.length; i++) { cTokens[i] = IBToken(bTokens[i]).cToken(); } address[] memory holders = new address[](1); holders[0] = address(this); IComptroller comptroller = IComptroller(registry.comptroller()); comptroller.claimComp(holders, cTokens, borrowers, suppliers); transferCOMP(); } function transferCOMP() public { address owner = registry.ownerOf(address(this)); IERC20 comp = IERC20(registry.comp()); comp.safeTransfer(owner, comp.balanceOf(address(this))); } function getAccountLiquidity(address oracle) external view returns (uint err, uint liquidity, uint shortFall) { return _getAccountLiquidity(oracle); } function getAccountLiquidity() external view returns (uint err, uint liquidity, uint shortFall) { IComptroller comptroller = IComptroller(registry.comptroller()); return _getAccountLiquidity(comptroller.oracle()); } function _getAccountLiquidity(address oracle) internal view returns (uint err, uint liquidity, uint shortFall) { IComptroller comptroller = IComptroller(registry.comptroller()); // If not topped up, get the account liquidity from Comptroller (err, liquidity, shortFall) = comptroller.getAccountLiquidity(address(this)); if(!isToppedUp()) { return (err, liquidity, shortFall); } require(err == 0, "Err-in-account-liquidity"); uint256 price = IPriceOracle(oracle).getUnderlyingPrice(toppedUpCToken); uint256 toppedUpAmtInUSD = mulTrucate(toppedUpAmount, price); // liquidity = 0 and shortFall = 0 if(liquidity == toppedUpAmtInUSD) return(0, 0, 0); // when shortFall = 0 if(shortFall == 0 && liquidity > 0) { if(liquidity > toppedUpAmtInUSD) { liquidity = sub_(liquidity, toppedUpAmtInUSD); } else { shortFall = sub_(toppedUpAmtInUSD, liquidity); liquidity = 0; } } else { // Handling case when compound returned liquidity = 0 and shortFall >= 0 shortFall = add_(shortFall, toppedUpAmtInUSD); } } } // File: contracts/bprotocol/interfaces/IAvatar.sol pragma solidity 0.5.16; contract IAvatarERC20 { function transfer(address cToken, address dst, uint256 amount) external returns (bool); function transferFrom(address cToken, address src, address dst, uint256 amount) external returns (bool); function approve(address cToken, address spender, uint256 amount) public returns (bool); } contract IAvatar is IAvatarERC20 { function initialize(address _registry, address comp, address compVoter) external; function quit() external returns (bool); function canUntop() public returns (bool); function toppedUpCToken() external returns (address); function toppedUpAmount() external returns (uint256); function redeem(address cToken, uint256 redeemTokens, address payable userOrDelegatee) external returns (uint256); function redeemUnderlying(address cToken, uint256 redeemAmount, address payable userOrDelegatee) external returns (uint256); function borrow(address cToken, uint256 borrowAmount, address payable userOrDelegatee) external returns (uint256); function borrowBalanceCurrent(address cToken) external returns (uint256); function collectCToken(address cToken, address from, uint256 cTokenAmt) public; function liquidateBorrow(uint repayAmount, address cTokenCollateral) external payable returns (uint256); // Comptroller functions function enterMarket(address cToken) external returns (uint256); function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function claimComp() external; function claimComp(address[] calldata bTokens) external; function claimComp(address[] calldata bTokens, bool borrowers, bool suppliers) external; function getAccountLiquidity() external view returns (uint err, uint liquidity, uint shortFall); } // Workaround for issue https://github.com/ethereum/solidity/issues/526 // CEther contract IAvatarCEther is IAvatar { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } // CErc20 contract IAvatarCErc20 is IAvatar { function mint(address cToken, uint256 mintAmount) external returns (uint256); function repayBorrow(address cToken, uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address cToken, address borrower, uint256 repayAmount) external returns (uint256); } contract ICushion { function liquidateBorrow(uint256 underlyingAmtToLiquidate, uint256 amtToDeductFromTopup, address cTokenCollateral) external payable returns (uint256); function canLiquidate() external returns (bool); function untop(uint amount) external; function toppedUpAmount() external returns (uint); function remainingLiquidationAmount() external returns(uint); function getMaxLiquidationAmount(address debtCToken) public returns (uint256); } contract ICushionCErc20 is ICushion { function topup(address cToken, uint256 topupAmount) external; } contract ICushionCEther is ICushion { function topup() external payable; } // File: contracts/bprotocol/interfaces/IBComptroller.sol pragma solidity 0.5.16; interface IBComptroller { function isCToken(address cToken) external view returns (bool); function isBToken(address bToken) external view returns (bool); function c2b(address cToken) external view returns (address); function b2c(address bToken) external view returns (address); } // File: contracts/bprotocol/avatar/AbsCToken.sol pragma solidity 0.5.16; contract AbsCToken is AbsAvatarBase { modifier onlyBToken() { _allowOnlyBToken(); _; } function _allowOnlyBToken() internal view { require(isValidBToken(msg.sender), "only-BToken-authorized"); } function isValidBToken(address bToken) internal view returns (bool) { IBComptroller bComptroller = IBComptroller(registry.bComptroller()); return bComptroller.isBToken(bToken); } function borrowBalanceCurrent(ICToken cToken) public onlyBToken returns (uint256) { uint256 borrowBalanceCurr = cToken.borrowBalanceCurrent(address(this)); if(toppedUpCToken == cToken) return add_(borrowBalanceCurr, toppedUpAmount); return borrowBalanceCurr; } function _toUnderlying(ICToken cToken, uint256 redeemTokens) internal returns (uint256) { uint256 exchangeRate = cToken.exchangeRateCurrent(); return mulTrucate(redeemTokens, exchangeRate); } // CEther // ====== function mint() public payable onlyBToken postPoolOp(false) { ICEther cEther = ICEther(registry.cEther()); cEther.mint.value(msg.value)(); // fails on compound in case of err if(! quit) _score().updateCollScore(address(this), address(cEther), toInt256(msg.value)); } function repayBorrow() external payable onlyBToken postPoolOp(false) { ICEther cEther = ICEther(registry.cEther()); uint256 amtToRepayOnCompound = _untopBeforeRepay(cEther, msg.value); if(amtToRepayOnCompound > 0) cEther.repayBorrow.value(amtToRepayOnCompound)(); // fails on compound in case of err if(! quit) _score().updateDebtScore(address(this), address(cEther), -toInt256(msg.value)); } // CErc20 // ====== function mint(ICErc20 cToken, uint256 mintAmount) public onlyBToken postPoolOp(false) returns (uint256) { IERC20 underlying = cToken.underlying(); underlying.safeApprove(address(cToken), mintAmount); uint result = cToken.mint(mintAmount); require(result == 0, "mint-fail"); if(! quit) _score().updateCollScore(address(this), address(cToken), toInt256(mintAmount)); return result; } function repayBorrow(ICErc20 cToken, uint256 repayAmount) external onlyBToken postPoolOp(false) returns (uint256) { uint256 amtToRepayOnCompound = _untopBeforeRepay(cToken, repayAmount); uint256 result = 0; if(amtToRepayOnCompound > 0) { IERC20 underlying = cToken.underlying(); // use resetApprove() in case ERC20.approve() has front-running attack protection underlying.safeApprove(address(cToken), amtToRepayOnCompound); result = cToken.repayBorrow(amtToRepayOnCompound); require(result == 0, "repayBorrow-fail"); if(! quit) _score().updateDebtScore(address(this), address(cToken), -toInt256(repayAmount)); } return result; // in case of err, tx fails at BToken } // CEther / CErc20 // =============== function liquidateBorrow( uint256 underlyingAmtToLiquidateDebt, uint256 amtToDeductFromTopup, ICToken cTokenColl ) external payable returns (uint256) { // 1. Can liquidate? require(canLiquidate(), "cant-liquidate"); ICToken cTokenDebt = toppedUpCToken; uint256 seizedCTokensColl = _doLiquidateBorrow(cTokenDebt, underlyingAmtToLiquidateDebt, amtToDeductFromTopup, cTokenColl); // Convert seizedCToken to underlyingTokens uint256 underlyingSeizedTokensColl = _toUnderlying(cTokenColl, seizedCTokensColl); if(! quit) { IScore score = _score(); score.updateCollScore(address(this), address(cTokenColl), -toInt256(underlyingSeizedTokensColl)); score.updateDebtScore(address(this), address(cTokenDebt), -toInt256(underlyingAmtToLiquidateDebt)); } return 0; } function redeem( ICToken cToken, uint256 redeemTokens, address payable userOrDelegatee ) external onlyBToken postPoolOp(true) returns (uint256) { uint256 result = cToken.redeem(redeemTokens); require(result == 0, "redeem-fail"); uint256 underlyingRedeemAmount = _toUnderlying(cToken, redeemTokens); if(! quit) _score().updateCollScore(address(this), address(cToken), -toInt256(underlyingRedeemAmount)); // Do the fund transfer at last if(_isCEther(cToken)) { userOrDelegatee.transfer(address(this).balance); } else { IERC20 underlying = cToken.underlying(); uint256 redeemedAmount = underlying.balanceOf(address(this)); underlying.safeTransfer(userOrDelegatee, redeemedAmount); } return result; } function redeemUnderlying( ICToken cToken, uint256 redeemAmount, address payable userOrDelegatee ) external onlyBToken postPoolOp(true) returns (uint256) { uint256 result = cToken.redeemUnderlying(redeemAmount); require(result == 0, "redeemUnderlying-fail"); if(! quit) _score().updateCollScore(address(this), address(cToken), -toInt256(redeemAmount)); // Do the fund transfer at last if(_isCEther(cToken)) { userOrDelegatee.transfer(redeemAmount); } else { IERC20 underlying = cToken.underlying(); underlying.safeTransfer(userOrDelegatee, redeemAmount); } return result; } function borrow( ICToken cToken, uint256 borrowAmount, address payable userOrDelegatee ) external onlyBToken postPoolOp(true) returns (uint256) { uint256 result = cToken.borrow(borrowAmount); require(result == 0, "borrow-fail"); if(! quit) _score().updateDebtScore(address(this), address(cToken), toInt256(borrowAmount)); // send funds at last if(_isCEther(cToken)) { userOrDelegatee.transfer(borrowAmount); } else { IERC20 underlying = cToken.underlying(); underlying.safeTransfer(userOrDelegatee, borrowAmount); } return result; } // ERC20 // ====== function transfer(ICToken cToken, address dst, uint256 amount) public onlyBToken postPoolOp(true) returns (bool) { address dstAvatar = registry.getAvatar(dst); bool result = cToken.transfer(dstAvatar, amount); require(result, "transfer-fail"); uint256 underlyingRedeemAmount = _toUnderlying(cToken, amount); IScore score = _score(); if(! quit) score.updateCollScore(address(this), address(cToken), -toInt256(underlyingRedeemAmount)); if(! IAvatar(dstAvatar).quit()) score.updateCollScore(dstAvatar, address(cToken), toInt256(underlyingRedeemAmount)); return result; } function transferFrom(ICToken cToken, address src, address dst, uint256 amount) public onlyBToken postPoolOp(true) returns (bool) { address srcAvatar = registry.getAvatar(src); address dstAvatar = registry.getAvatar(dst); bool result = cToken.transferFrom(srcAvatar, dstAvatar, amount); require(result, "transferFrom-fail"); require(IAvatar(srcAvatar).canUntop(), "insuffecient-fund-at-src"); uint256 underlyingRedeemAmount = _toUnderlying(cToken, amount); IScore score = _score(); if(! IAvatar(srcAvatar).quit()) score.updateCollScore(srcAvatar, address(cToken), -toInt256(underlyingRedeemAmount)); if(! IAvatar(dstAvatar).quit()) score.updateCollScore(dstAvatar, address(cToken), toInt256(underlyingRedeemAmount)); return result; } function approve(ICToken cToken, address spender, uint256 amount) public onlyBToken returns (bool) { address spenderAvatar = registry.getAvatar(spender); return cToken.approve(spenderAvatar, amount); } function collectCToken(ICToken cToken, address from, uint256 cTokenAmt) public postPoolOp(false) { // `from` should not be an avatar require(registry.ownerOf(from) == address(0), "from-is-an-avatar"); require(cToken.transferFrom(from, address(this), cTokenAmt), "transferFrom-fail"); uint256 underlyingAmt = _toUnderlying(cToken, cTokenAmt); if(! quit) _score().updateCollScore(address(this), address(cToken), toInt256(underlyingAmt)); } /** * @dev Fallback to receieve ETH from CEther contract on `borrow()`, `redeem()`, `redeemUnderlying` */ function () external payable { // Receive ETH } } // File: contracts/bprotocol/interfaces/IComp.sol pragma solidity 0.5.16; interface IComp { function delegate(address delegatee) external; } // File: contracts/bprotocol/avatar/Avatar.sol pragma solidity 0.5.16; contract ProxyStorage { address internal masterCopy; } /** * @title An Avatar contract deployed per account. The contract holds cTokens and directly interacts * with Compound finance. * @author Smart Future Labs Ltd. */ contract Avatar is ProxyStorage, AbsComptroller, AbsCToken { // @NOTICE: NO CONSTRUCTOR AS ITS USED AS AN IMPLEMENTATION CONTRACT FOR PROXY /** * @dev Initialize the contract variables * @param _registry Registry contract address */ function initialize(address _registry, address /*comp*/, address /*compVoter*/) external { _initAvatarBase(_registry); } //override /** * @dev Mint cETH using ETH and enter market on Compound * @notice onlyBToken can call this function, as `super.mint()` is protected with `onlyBToken` modifier */ function mint() public payable { ICEther cEther = ICEther(registry.cEther()); require(_enterMarket(address(cEther)) == 0, "enterMarket-fail"); super.mint(); } //override /** * @dev Mint cToken for ERC20 and enter market on Compound * @notice onlyBToken can call this function, as `super.mint()` is protected with `onlyBToken` modifier */ function mint(ICErc20 cToken, uint256 mintAmount) public returns (uint256) { require(_enterMarket(address(cToken)) == 0, "enterMarket-fail"); uint256 result = super.mint(cToken, mintAmount); return result; } // EMERGENCY FUNCTIONS function emergencyCall(address payable target, bytes calldata data) external payable onlyAvatarOwner { uint first4Bytes = uint(uint8(data[0])) << 24 | uint(uint8(data[1])) << 16 | uint(uint8(data[2])) << 8 | uint(uint8(data[3])) << 0; bytes4 functionSig = bytes4(uint32(first4Bytes)); require(quit || registry.whitelistedAvatarCalls(target, functionSig), "not-listed"); (bool succ, bytes memory err) = target.call.value(msg.value)(data); require(succ, string(err)); } }
1. Is toppedUp OR partially liquidated CEther CErc20 take tokens from pool contract
function _doLiquidateBorrow( ICToken debtCToken, uint256 underlyingAmtToLiquidate, uint256 amtToDeductFromTopup, ICToken collCToken ) internal onlyPool returns (uint256) { address payable poolContract = pool(); bool partiallyLiquidated = isPartiallyLiquidated(); require(isToppedUp() || partiallyLiquidated, "cant-perform-liquidateBorrow"); if(partiallyLiquidated) { require(debtCToken == liquidationCToken, "debtCToken!=liquidationCToken"); require(debtCToken == toppedUpCToken, "debtCToken!=toppedUpCToken"); liquidationCToken = debtCToken; } if(!partiallyLiquidated) { remainingLiquidationAmount = getMaxLiquidationAmount(debtCToken); } uint256 amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup); if(amtToRepayOnCompound > 0) { bool isCEtherDebt = _isCEther(debtCToken); if(isCEtherDebt) { require(msg.value == amtToRepayOnCompound, "insuffecient-ETH-sent"); ICEther cEther = ICEther(registry.cEther()); cEther.repayBorrow.value(amtToRepayOnCompound)(); IERC20 underlying = toppedUpCToken.underlying(); underlying.safeTransferFrom(poolContract, address(this), amtToRepayOnCompound); underlying.safeApprove(address(debtCToken), amtToRepayOnCompound); require(ICErc20(address(debtCToken)).repayBorrow(amtToRepayOnCompound) == 0, "repayBorrow-fail"); } } require(toppedUpAmount >= amtToDeductFromTopup, "amtToDeductFromTopup>toppedUpAmount"); toppedUpAmount = sub_(toppedUpAmount, amtToDeductFromTopup); (uint err, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(debtCToken), address(collCToken), underlyingAmtToLiquidate ); require(err == 0, "err-liquidateCalculateSeizeTokens"); return seizeTokens; }
1,244,226
pragma solidity ^0.5.3; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { 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 strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string memory) { 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); } } contract AccessControl { address payable public creatorAddress; uint16 public totalSeraphims = 0; mapping (address => bool) public seraphims; bool public isMaintenanceMode = true; modifier onlyCREATOR() { require(msg.sender == creatorAddress); _; } modifier onlySERAPHIM() { require(seraphims[msg.sender] == true); _; } modifier isContractActive { require(!isMaintenanceMode); _; } // Constructor constructor() public { creatorAddress = msg.sender; } //Seraphims are contracts or addresses that have write access function addSERAPHIM(address _newSeraphim) onlyCREATOR public { if (seraphims[_newSeraphim] == false) { seraphims[_newSeraphim] = true; totalSeraphims += 1; } } function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public { if (seraphims[_oldSeraphim] == true) { seraphims[_oldSeraphim] = false; totalSeraphims -= 1; } } function updateMaintenanceMode(bool _isMaintaining) onlyCREATOR public { isMaintenanceMode = _isMaintaining; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } function getRandomNumber(uint16 maxRandom, uint8 min, address privateAddress) view public returns(uint8) { uint256 genNum = uint256(blockhash(block.number-1)) + uint256(privateAddress); return uint8(genNum % (maxRandom - min + 1)+min); } } /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. 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 _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes4 _data ) public returns(bytes4); } contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract iABToken is AccessControl{ function balanceOf(address owner) public view returns (uint256); function totalSupply() external view returns (uint256) ; function ownerOf(uint256 tokenId) public view returns (address) ; function setMaxAngels() external; function setMaxAccessories() external; function setMaxMedals() external ; function initAngelPrices() external; function initAccessoryPrices() external ; function setCardSeriesPrice(uint8 _cardSeriesId, uint _newPrice) external; function approve(address to, uint256 tokenId) public; function getRandomNumber(uint16 maxRandom, uint8 min, address privateAddress) view public returns(uint8) ; function tokenURI(uint256 _tokenId) public pure returns (string memory) ; function baseTokenURI() public pure returns (string memory) ; function name() external pure returns (string memory _name) ; function symbol() external pure returns (string memory _symbol) ; function getApproved(uint256 tokenId) public view returns (address) ; function setApprovalForAll(address to, bool approved) public ; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public ; function safeTransferFrom(address from, address to, uint256 tokenId) public ; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public ; function _exists(uint256 tokenId) internal view returns (bool) ; function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) ; function _mint(address to, uint256 tokenId) internal ; function mintABToken(address owner, uint8 _cardSeriesId, uint16 _power, uint16 _auraRed, uint16 _auraYellow, uint16 _auraBlue, string memory _name, uint16 _experience, uint16 _oldId) public; function addABTokenIdMapping(address _owner, uint256 _tokenId) private ; function getPrice(uint8 _cardSeriesId) public view returns (uint); function buyAngel(uint8 _angelSeriesId) public payable ; function buyAccessory(uint8 _accessorySeriesId) public payable ; function getAura(uint8 _angelSeriesId) pure public returns (uint8 auraRed, uint8 auraYellow, uint8 auraBlue) ; function getAngelPower(uint8 _angelSeriesId) private view returns (uint16) ; function getABToken(uint256 tokenId) view public returns(uint8 cardSeriesId, uint16 power, uint16 auraRed, uint16 auraYellow, uint16 auraBlue, string memory name, uint16 experience, uint64 lastBattleTime, uint16 lastBattleResult, address owner, uint16 oldId); function setAuras(uint256 tokenId, uint16 _red, uint16 _blue, uint16 _yellow) external; function setName(uint256 tokenId,string memory namechange) public ; function setExperience(uint256 tokenId, uint16 _experience) external; function setLastBattleResult(uint256 tokenId, uint16 _result) external ; function setLastBattleTime(uint256 tokenId) external; function setLastBreedingTime(uint256 tokenId) external ; function setoldId(uint256 tokenId, uint16 _oldId) external; function getABTokenByIndex(address _owner, uint64 _index) view external returns(uint256) ; function _burn(address owner, uint256 tokenId) internal ; function _burn(uint256 tokenId) internal ; function _transferFrom(address from, address to, uint256 tokenId) internal ; function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool); function _clearApproval(uint256 tokenId) private ; } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ABToken is IERC721, iABToken, ERC165 { using SafeMath for uint256; using SafeMath for uint8; using Address for address; uint256 public totalTokens; //Mapping or which IDs each address owns mapping(address => uint256[]) public ownerABTokenCollection; // 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 token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ //current and max numbers of issued tokens for each series uint32[100] public currentTokenNumbers; uint32[100] public maxTokenNumbers; //current price of each angel and accessory series uint[24] public angelPrice; uint[18] public accessoryPrice; address proxyRegistryAddress; // Main data structure for each token struct ABCard { uint256 tokenId; uint8 cardSeriesId; //This is 0 to 23 for angels, 24 to 42 for pets, 43 to 60 for accessories, 61 to 72 for medals //address owner; //already accounted in mapping. uint16 power; //This number is luck for pets and battlepower for angels uint16 auraRed; uint16 auraYellow; uint16 auraBlue; string name; uint16 experience; uint64 lastBattleTime; uint64 lastBreedingTime; uint16 lastBattleResult; uint16 oldId; //for cards transfered from the first version of the game. } //Main mapping storing an ABCard for each token ID mapping(uint256 => ABCard) public ABTokenCollection; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } function totalSupply() external view returns (uint256) { return totalTokens; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } //Initial function to set the maximum numbers of each angel card function setMaxAngels() external onlyCREATOR { uint i =0; //Angels 0 and 1 have no max //Lucifer and Michael have max numbers 250 maxTokenNumbers[2] = 250; maxTokenNumbers[3] = 250; maxTokenNumbers[4] = 45; maxTokenNumbers[5] = 50; for (i=6; i<15; i++) { maxTokenNumbers[i]= 45; } for (i=15; i<24; i++) { maxTokenNumbers[i]= 65; } } //Initial function to set the maximum number of accessories function setMaxAccessories() external onlyCREATOR { uint i = 0; for (i=43; i<60; i++) { maxTokenNumbers[i]= 200; } } //Initial function to set the max number of medals function setMaxMedals() onlyCREATOR external { maxTokenNumbers[61] = 5000; maxTokenNumbers[62] = 5000; maxTokenNumbers[63] = 5000; maxTokenNumbers[64] = 5000; maxTokenNumbers[65] = 500; maxTokenNumbers[66] = 500; maxTokenNumbers[67] = 200; maxTokenNumbers[68] = 200; maxTokenNumbers[69] = 200; maxTokenNumbers[70] = 100; maxTokenNumbers[71] = 100; maxTokenNumbers[72] = 50; } //Function called once at the beginning to set the prices of all the angel cards. function initAngelPrices() external onlyCREATOR { angelPrice[0] = 0; angelPrice[1] = 30000000000000000; angelPrice[2] = 666000000000000000; angelPrice[3] = 800000000000000000; angelPrice[4] = 10000000000000000; angelPrice[5] = 10000000000000000; angelPrice[6] = 20000000000000000; angelPrice[7] = 25000000000000000; angelPrice[8] = 16000000000000000; angelPrice[9] = 18000000000000000; angelPrice[10] = 14000000000000000; angelPrice[11] = 20000000000000000; angelPrice[12] = 24000000000000000; angelPrice[13] = 28000000000000000; angelPrice[14] = 40000000000000000; angelPrice[15] = 50000000000000000; angelPrice[16] = 53000000000000000; angelPrice[17] = 60000000000000000; angelPrice[18] = 65000000000000000; angelPrice[19] = 70000000000000000; angelPrice[20] = 75000000000000000; angelPrice[21] = 80000000000000000; angelPrice[22] = 85000000000000000; angelPrice[23] = 90000000000000000; } //Function called once at the beginning to set the prices of all the accessory cards. function initAccessoryPrices() external onlyCREATOR { accessoryPrice[0] = 20000000000000000; accessoryPrice[1] = 60000000000000000; accessoryPrice[2] = 40000000000000000; accessoryPrice[3] = 90000000000000000; accessoryPrice[4] = 80000000000000000; accessoryPrice[5] = 160000000000000000; accessoryPrice[6] = 60000000000000000; accessoryPrice[7] = 120000000000000000; accessoryPrice[8] = 60000000000000000; accessoryPrice[9] = 120000000000000000; accessoryPrice[10] = 60000000000000000; accessoryPrice[11] = 120000000000000000; accessoryPrice[12] = 200000000000000000; accessoryPrice[13] = 200000000000000000; accessoryPrice[14] = 200000000000000000; accessoryPrice[15] = 200000000000000000; accessoryPrice[16] = 500000000000000000; accessoryPrice[17] = 600000000000000000; } // Developer function to change the price (in wei) for a card series. function setCardSeriesPrice(uint8 _cardSeriesId, uint _newPrice) external onlyCREATOR { if (_cardSeriesId <24) {angelPrice[_cardSeriesId] = _newPrice;} else { if ((_cardSeriesId >42) && (_cardSeriesId < 61)) {accessoryPrice[(_cardSeriesId-43)] = _newPrice;} } } function withdrawEther() external onlyCREATOR { creatorAddress.transfer(address(this).balance); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function getRandomNumber(uint16 maxRandom, uint8 min, address privateAddress) view public returns(uint8) { uint256 genNum = uint256(blockhash(block.number-1)) + uint256(privateAddress); return uint8(genNum % (maxRandom - min + 1)+min); } /** * @dev Returns an URI for a given token ID */ function tokenURI(uint256 _tokenId) public pure returns (string memory) { return Strings.strConcat( baseTokenURI(), Strings.uint2str(_tokenId) ); } function baseTokenURI() public pure returns (string memory) { return "https://www.angelbattles.com/URI/"; } /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string memory _name) { return "Angel Battle Token"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string memory _symbol) { return "ABT"; } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); addABTokenIdMapping(to, tokenId); emit Transfer(address(0), to, tokenId); } function mintABToken(address owner, uint8 _cardSeriesId, uint16 _power, uint16 _auraRed, uint16 _auraYellow, uint16 _auraBlue, string memory _name, uint16 _experience, uint16 _oldId) public onlySERAPHIM { require((currentTokenNumbers[_cardSeriesId] < maxTokenNumbers[_cardSeriesId] || maxTokenNumbers[_cardSeriesId] == 0)); require(_cardSeriesId <100); ABCard storage abcard = ABTokenCollection[totalTokens]; abcard.power = _power; abcard.cardSeriesId= _cardSeriesId; abcard.auraRed = _auraRed; abcard.auraYellow= _auraYellow; abcard.auraBlue= _auraBlue; abcard.name = _name; abcard.experience = _experience; abcard.tokenId = totalTokens; abcard.lastBattleTime = uint64(now); abcard.lastBreedingTime = uint64(now); abcard.lastBattleResult = 0; abcard.oldId = _oldId; _mint(owner, totalTokens); totalTokens = totalTokens +1; currentTokenNumbers[_cardSeriesId] ++; } function _mintABToken(address owner, uint8 _cardSeriesId, uint16 _power, uint16 _auraRed, uint16 _auraYellow, uint16 _auraBlue, string memory _name, uint16 _experience, uint16 _oldId) internal { require((currentTokenNumbers[_cardSeriesId] < maxTokenNumbers[_cardSeriesId] || maxTokenNumbers[_cardSeriesId] == 0)); require(_cardSeriesId <100); ABCard storage abcard = ABTokenCollection[totalTokens]; abcard.power = _power; abcard.cardSeriesId= _cardSeriesId; abcard.auraRed = _auraRed; abcard.auraYellow= _auraYellow; abcard.auraBlue= _auraBlue; abcard.name = _name; abcard.experience = _experience; abcard.tokenId = totalTokens; abcard.lastBattleTime = uint64(now); abcard.lastBreedingTime = uint64(now); abcard.lastBattleResult = 0; abcard.oldId = _oldId; _mint(owner, totalTokens); totalTokens = totalTokens +1; currentTokenNumbers[_cardSeriesId] ++; } function addABTokenIdMapping(address _owner, uint256 _tokenId) private { uint256[] storage owners = ownerABTokenCollection[_owner]; owners.push(_tokenId); } function getPrice(uint8 _cardSeriesId) public view returns (uint) { if (_cardSeriesId <24) {return angelPrice[_cardSeriesId];} if ((_cardSeriesId >42) && (_cardSeriesId < 61)) {return accessoryPrice[(_cardSeriesId-43)];} return 0; } function buyAngel(uint8 _angelSeriesId) public payable { //don't create another card if we are already at the max if ((maxTokenNumbers[_angelSeriesId] <= currentTokenNumbers[_angelSeriesId]) && (_angelSeriesId >1 )) {revert();} //don't create another card if they haven't sent enough money. if (msg.value < angelPrice[_angelSeriesId]) {revert();} //don't create an angel card if they are trying to create a different type of card. if ((_angelSeriesId<0) || (_angelSeriesId > 23)) {revert();} uint8 auraRed; uint8 auraYellow; uint8 auraBlue; uint16 power; (auraRed, auraYellow, auraBlue) = getAura(_angelSeriesId); (power) = getAngelPower(_angelSeriesId); _mintABToken(msg.sender, _angelSeriesId, power, auraRed, auraYellow, auraBlue,"", 0, 0); } function buyAccessory(uint8 _accessorySeriesId) public payable { //don't create another card if we are already at the max if (maxTokenNumbers[_accessorySeriesId] <= currentTokenNumbers[_accessorySeriesId]) {revert();} //don't create another card if they haven't sent enough money. if (msg.value < accessoryPrice[_accessorySeriesId-43]) {revert();} //don't create a card if they are trying to create a different type of card. if ((_accessorySeriesId<43) || (_accessorySeriesId > 60)) {revert();} _mintABToken(msg.sender,_accessorySeriesId, 0, 0, 0, 0, "",0, 0); } //Returns the Aura color of each angel function getAura(uint8 _angelSeriesId) pure public returns (uint8 auraRed, uint8 auraYellow, uint8 auraBlue) { if (_angelSeriesId == 0) {return(0,0,1);} if (_angelSeriesId == 1) {return(0,1,0);} if (_angelSeriesId == 2) {return(1,0,1);} if (_angelSeriesId == 3) {return(1,1,0);} if (_angelSeriesId == 4) {return(1,0,0);} if (_angelSeriesId == 5) {return(0,1,0);} if (_angelSeriesId == 6) {return(1,0,1);} if (_angelSeriesId == 7) {return(0,1,1);} if (_angelSeriesId == 8) {return(1,1,0);} if (_angelSeriesId == 9) {return(0,0,1);} if (_angelSeriesId == 10) {return(1,0,0);} if (_angelSeriesId == 11) {return(0,1,0);} if (_angelSeriesId == 12) {return(1,0,1);} if (_angelSeriesId == 13) {return(0,1,1);} if (_angelSeriesId == 14) {return(1,1,0);} if (_angelSeriesId == 15) {return(0,0,1);} if (_angelSeriesId == 16) {return(1,0,0);} if (_angelSeriesId == 17) {return(0,1,0);} if (_angelSeriesId == 18) {return(1,0,1);} if (_angelSeriesId == 19) {return(0,1,1);} if (_angelSeriesId == 20) {return(1,1,0);} if (_angelSeriesId == 21) {return(0,0,1);} if (_angelSeriesId == 22) {return(1,0,0);} if (_angelSeriesId == 23) {return(0,1,1);} } function getAngelPower(uint8 _angelSeriesId) private view returns (uint16) { uint8 randomPower = getRandomNumber(10,0,msg.sender); if (_angelSeriesId >=4) { return (100 + 10 * ((_angelSeriesId - 4) + randomPower)); } if (_angelSeriesId == 0 ) { return (50 + randomPower); } if (_angelSeriesId == 1) { return (120 + randomPower); } if (_angelSeriesId == 2) { return (250 + randomPower); } if (_angelSeriesId == 3) { return (300 + randomPower); } } function getCurrentTokenNumbers(uint8 _cardSeriesId) view public returns (uint32) { return currentTokenNumbers[_cardSeriesId]; } function getMaxTokenNumbers(uint8 _cardSeriesId) view public returns (uint32) { return maxTokenNumbers[_cardSeriesId]; } function getABToken(uint256 tokenId) view public returns(uint8 cardSeriesId, uint16 power, uint16 auraRed, uint16 auraYellow, uint16 auraBlue, string memory name, uint16 experience, uint64 lastBattleTime, uint16 lastBattleResult, address owner, uint16 oldId) { ABCard memory abcard = ABTokenCollection[tokenId]; cardSeriesId = abcard.cardSeriesId; power = abcard.power; experience = abcard.experience; auraRed = abcard.auraRed; auraBlue = abcard.auraBlue; auraYellow = abcard.auraYellow; name = abcard.name; lastBattleTime = abcard.lastBattleTime; lastBattleResult = abcard.lastBattleResult; oldId = abcard.oldId; owner = ownerOf(tokenId); } function setAuras(uint256 tokenId, uint16 _red, uint16 _blue, uint16 _yellow) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.auraRed = _red; abcard.auraYellow = _yellow; abcard.auraBlue = _blue; } } function setName(uint256 tokenId,string memory namechange) public { ABCard storage abcard = ABTokenCollection[tokenId]; if (msg.sender != ownerOf(tokenId)) {revert();} if (abcard.tokenId == tokenId) { abcard.name = namechange; } } function setExperience(uint256 tokenId, uint16 _experience) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.experience = _experience; } } function setLastBattleResult(uint256 tokenId, uint16 _result) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.lastBattleResult = _result; } } function setLastBattleTime(uint256 tokenId) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.lastBattleTime = uint64(now); } } function setLastBreedingTime(uint256 tokenId) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.lastBreedingTime = uint64(now); } } function setoldId(uint256 tokenId, uint16 _oldId) external onlySERAPHIM { ABCard storage abcard = ABTokenCollection[tokenId]; if (abcard.tokenId == tokenId) { abcard.oldId = _oldId; } } function getABTokenByIndex(address _owner, uint64 _index) view external returns(uint256) { if (_index >= ownerABTokenCollection[_owner].length) { return 0; } return ownerABTokenCollection[_owner][_index]; } /** * @dev external function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned * Only the owner can burn their token. */ function burn(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender); _clearApproval(tokenId); _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].sub(1); _tokenOwner[tokenId] = address(0); emit Transfer(msg.sender, address(0), tokenId); } /** * @dev external function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned * Only the owner can burn their token. * This function allows a new token type to be reissued. This preserves rarity, while the burn functio increases rarity */ function burnAndRecycle(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender); uint8 cardSeriesId; _clearApproval(tokenId); _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].sub(1); _tokenOwner[tokenId] = address(0); (cardSeriesId,,,,,,,,,,) = getABToken (tokenId); if (currentTokenNumbers[cardSeriesId] >= 1) { currentTokenNumbers[cardSeriesId] = currentTokenNumbers[cardSeriesId] - 1; } emit Transfer(msg.sender, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); _clearApproval(tokenId); _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; addABTokenIdMapping(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
Approves another address to transfer the given token ID The zero address indicates there is no approved address. There can only be one approved address per token at a given time. Can only be called by the token owner or an approved operator. to address to be approved for the given token ID tokenId uint256 ID of the token to be approved/
function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
5,403,953
./full_match/5/0xd0F20b37E450bBcf8ac2566FA42Ab1A0E42aB8F1/sources/StolenMemes.sol
when this address can be stolen from can never steal from uni pair or empty wallet
function wenStealFrom(address _address) public view returns (uint256) { if (_address == uniPair || balanceOf(_address) == 0) { return type(uint256).max; } return memeStealers[_address].lastTransferTime + timeFromTransfer; }
1,871,218
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) public view returns (uint256) {
1,784,033
pragma solidity 0.5.15; // YAM v3 Token Proxy library safemath64 { //inject NONSTANDARD NAMING function ADD91(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB43(a, b, "SafeMath: subtraction overflow"); } function SUB43(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL53(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV50(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV50(a, b, "SafeMath: division by zero"); } function DIV50(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD67(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD67(a, b, "SafeMath: modulo by zero"); } function MOD67(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // Storage for a YAM token contract yamtokenstorage62 { //inject NONSTANDARD NAMING using safemath64 for uint256; bool internal _notEntered; string public name; string public symbol; uint8 public decimals; address public gov; address public pendingGov; address public rebaser; address public migrator; address public incentivizer; uint256 public totalSupply; uint256 public constant internaldecimals9 = 10**24; //inject NONSTANDARD NAMING uint256 public constant base99 = 10**18; //inject NONSTANDARD NAMING uint256 public yamsScalingFactor; mapping (address => uint256) internal _yamBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant permit_typehash49 = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; //inject NONSTANDARD NAMING bytes32 public DOMAIN_SEPARATOR; } contract yamgovernancestorage60 { //inject NONSTANDARD NAMING mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant domain_typehash51 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING bytes32 public constant delegation_typehash89 = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); //inject NONSTANDARD NAMING mapping (address => uint) public nonces; } contract yamtokeninterface94 is yamtokenstorage62, yamgovernancestorage60 { //inject NONSTANDARD NAMING event DELEGATECHANGED94(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); //inject NONSTANDARD NAMING event DELEGATEVOTESCHANGED9(address indexed delegate, uint previousBalance, uint newBalance); //inject NONSTANDARD NAMING event REBASE47(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor); //inject NONSTANDARD NAMING event NEWPENDINGGOV65(address oldPendingGov, address newPendingGov); //inject NONSTANDARD NAMING event NEWGOV96(address oldGov, address newGov); //inject NONSTANDARD NAMING event NEWREBASER58(address oldRebaser, address newRebaser); //inject NONSTANDARD NAMING event NEWMIGRATOR62(address oldMigrator, address newMigrator); //inject NONSTANDARD NAMING event NEWINCENTIVIZER48(address oldIncentivizer, address newIncentivizer); //inject NONSTANDARD NAMING event TRANSFER90(address indexed from, address indexed to, uint amount); //inject NONSTANDARD NAMING event APPROVAL77(address indexed owner, address indexed spender, uint amount); //inject NONSTANDARD NAMING event MINT48(address to, uint256 amount); //inject NONSTANDARD NAMING // Public functions function TRANSFER1(address to, uint256 value) external returns(bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address from, address to, uint256 value) external returns(bool); //inject NONSTANDARD NAMING function BALANCEOF41(address who) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING78(address who) external view returns(uint256); //inject NONSTANDARD NAMING function ALLOWANCE40(address owner_, address spender) external view returns(uint256); //inject NONSTANDARD NAMING function APPROVE79(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function INCREASEALLOWANCE13(address spender, uint256 addedValue) external returns (bool); //inject NONSTANDARD NAMING function DECREASEALLOWANCE37(address spender, uint256 subtractedValue) external returns (bool); //inject NONSTANDARD NAMING function MAXSCALINGFACTOR18() external view returns (uint256); //inject NONSTANDARD NAMING function YAMTOFRAGMENT82(uint256 yam) external view returns (uint256); //inject NONSTANDARD NAMING function FRAGMENTTOYAM47(uint256 value) external view returns (uint256); //inject NONSTANDARD NAMING function GETPRIORVOTES37(address account, uint blockNumber) external view returns (uint256); //inject NONSTANDARD NAMING function DELEGATEBYSIG44(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function DELEGATE51(address delegatee) external; //inject NONSTANDARD NAMING function DELEGATES8(address delegator) external view returns (address); //inject NONSTANDARD NAMING function GETCURRENTVOTES74(address account) external view returns (uint256); //inject NONSTANDARD NAMING function MINT4(address to, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function REBASE13(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); //inject NONSTANDARD NAMING function _SETREBASER91(address rebaser_) external; //inject NONSTANDARD NAMING function _SETINCENTIVIZER31(address incentivizer_) external; //inject NONSTANDARD NAMING function _SETPENDINGGOV72(address pendingGov_) external; //inject NONSTANDARD NAMING function _ACCEPTGOV39() external; //inject NONSTANDARD NAMING } contract yamdelegationstorage25 { //inject NONSTANDARD NAMING address public implementation; } contract yamdelegatorinterface45 is yamdelegationstorage25 { //inject NONSTANDARD NAMING event NEWIMPLEMENTATION52(address oldImplementation, address newImplementation); //inject NONSTANDARD NAMING function _SETIMPLEMENTATION59(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; //inject NONSTANDARD NAMING } contract yamdelegator11 is yamtokeninterface94, yamdelegatorinterface45 { //inject NONSTANDARD NAMING constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initTotalSupply_, address implementation_, bytes memory becomeImplementationData ) public { // Creator of the contract is gov during initialization gov = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) DELEGATETO59( implementation_, abi.encodeWithSignature( "initialize(string,string,uint8,address,uint256)", name_, symbol_, decimals_, msg.sender, initTotalSupply_ ) ); // New implementations always get set via the settor (post-initialize) _SETIMPLEMENTATION59(implementation_, false, becomeImplementationData); } function _SETIMPLEMENTATION59(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { //inject NONSTANDARD NAMING require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov"); if (allowResign) { DELEGATETOIMPLEMENTATION54(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; DELEGATETOIMPLEMENTATION54(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NEWIMPLEMENTATION52(oldImplementation, implementation); } function MINT4(address to, uint256 mintAmount) //inject NONSTANDARD NAMING external returns (bool) { to; mintAmount; // Shh DELEGATEANDRETURN53(); } function TRANSFER1(address dst, uint256 amount) //inject NONSTANDARD NAMING external returns (bool) { dst; amount; // Shh DELEGATEANDRETURN53(); } function TRANSFERFROM54( //inject NONSTANDARD NAMING address src, address dst, uint256 amount ) external returns (bool) { src; dst; amount; // Shh DELEGATEANDRETURN53(); } function APPROVE79( //inject NONSTANDARD NAMING address spender, uint256 amount ) external returns (bool) { spender; amount; // Shh DELEGATEANDRETURN53(); } function INCREASEALLOWANCE13( //inject NONSTANDARD NAMING address spender, uint256 addedValue ) external returns (bool) { spender; addedValue; // Shh DELEGATEANDRETURN53(); } function MAXSCALINGFACTOR18() //inject NONSTANDARD NAMING external view returns (uint256) { DELEGATETOVIEWANDRETURN42(); } function REBASE13( //inject NONSTANDARD NAMING uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256) { epoch; indexDelta; positive; DELEGATEANDRETURN53(); } function DECREASEALLOWANCE37( //inject NONSTANDARD NAMING address spender, uint256 subtractedValue ) external returns (bool) { spender; subtractedValue; // Shh DELEGATEANDRETURN53(); } // --- Approve by signature --- function PERMIT89( //inject NONSTANDARD NAMING address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { owner; spender; value; deadline; v; r; s; // Shh DELEGATEANDRETURN53(); } function ALLOWANCE40( //inject NONSTANDARD NAMING address owner, address spender ) external view returns (uint256) { owner; spender; // Shh DELEGATETOVIEWANDRETURN42(); } function RESCUETOKENS5( //inject NONSTANDARD NAMING address token, address to, uint256 amount ) external returns (bool) { token; to; amount; // Shh DELEGATEANDRETURN53(); } function DELEGATES8( //inject NONSTANDARD NAMING address delegator ) external view returns (address) { delegator; // Shh DELEGATETOVIEWANDRETURN42(); } function BALANCEOF41(address owner) //inject NONSTANDARD NAMING external view returns (uint256) { owner; // Shh DELEGATETOVIEWANDRETURN42(); } function BALANCEOFUNDERLYING78(address owner) //inject NONSTANDARD NAMING external view returns (uint256) { owner; // Shh DELEGATETOVIEWANDRETURN42(); } function _SETPENDINGGOV72(address newPendingGov) //inject NONSTANDARD NAMING external { newPendingGov; // Shh DELEGATEANDRETURN53(); } function _SETREBASER91(address rebaser_) //inject NONSTANDARD NAMING external { rebaser_; // Shh DELEGATEANDRETURN53(); } function _SETINCENTIVIZER31(address incentivizer_) //inject NONSTANDARD NAMING external { incentivizer_; // Shh DELEGATEANDRETURN53(); } function _SETMIGRATOR24(address migrator_) //inject NONSTANDARD NAMING external { migrator_; // Shh DELEGATEANDRETURN53(); } function _ACCEPTGOV39() //inject NONSTANDARD NAMING external { DELEGATEANDRETURN53(); } function GETPRIORVOTES37(address account, uint blockNumber) //inject NONSTANDARD NAMING external view returns (uint256) { account; blockNumber; DELEGATETOVIEWANDRETURN42(); } function DELEGATEBYSIG44( //inject NONSTANDARD NAMING address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { delegatee; nonce; expiry; v; r; s; DELEGATEANDRETURN53(); } function DELEGATE51(address delegatee) //inject NONSTANDARD NAMING external { delegatee; DELEGATEANDRETURN53(); } function GETCURRENTVOTES74(address account) //inject NONSTANDARD NAMING external view returns (uint256) { account; DELEGATETOVIEWANDRETURN42(); } function YAMTOFRAGMENT82(uint256 yam) //inject NONSTANDARD NAMING external view returns (uint256) { yam; DELEGATETOVIEWANDRETURN42(); } function FRAGMENTTOYAM47(uint256 value) //inject NONSTANDARD NAMING external view returns (uint256) { value; DELEGATETOVIEWANDRETURN42(); } function DELEGATETO59(address callee, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } function DELEGATETOIMPLEMENTATION54(bytes memory data) public returns (bytes memory) { //inject NONSTANDARD NAMING return DELEGATETO59(implementation, data); } function DELEGATETOVIEWIMPLEMENTATION43(bytes memory data) public view returns (bytes memory) { //inject NONSTANDARD NAMING (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function DELEGATETOVIEWANDRETURN42() private view returns (bytes memory) { //inject NONSTANDARD NAMING (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) } } } function DELEGATEANDRETURN53() private returns (bytes memory) { //inject NONSTANDARD NAMING (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } function() external payable { require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation DELEGATEANDRETURN53(); } }
inject NONSTANDARD NAMING
function DIV50(uint256 a, uint256 b) internal pure returns (uint256) {
5,400,612
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IBMICoverStaking.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IRewardsGenerator.sol"; import "./interfaces/ILiquidityMining.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IBMIStaking.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./interfaces/IShieldMining.sol"; import "./tokens/ERC1155Upgradeable.sol"; import "./abstract/AbstractDependant.sol"; import "./abstract/AbstractSlasher.sol"; import "./Globals.sol"; contract BMICoverStaking is IBMICoverStaking, OwnableUpgradeable, ERC1155Upgradeable, AbstractDependant, AbstractSlasher { using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using SafeMath for uint256; using Math for uint256; IERC20 public bmiToken; IPolicyBookRegistry public policyBookRegistry; IRewardsGenerator public rewardsGenerator; ILiquidityMining public liquidityMining; IBMIStaking public bmiStaking; ILiquidityRegistry public liquidityRegistry; mapping(uint256 => StakingInfo) public override _stakersPool; // nft index -> info uint256 internal _nftMintId; // next nft mint id mapping(address => EnumerableSet.UintSet) internal _nftHolderTokens; // holder -> nfts EnumerableMap.UintToAddressMap internal _nftTokenOwners; // index nft -> holder // new state post v2 IShieldMining public shieldMining; bool public allowStakeProfit; address public bmiTreasury; event StakingNFTMinted(uint256 id, address policyBookAddress, address to); event StakingNFTBurned(uint256 id, address policyBookAddress); event StakingBMIProfitWithdrawn( uint256 id, address policyBookAddress, address to, uint256 amount ); event StakingFundsWithdrawn(uint256 id, address policyBookAddress, address to, uint256 amount); event TokensRecovered(address to, uint256 amount); modifier onlyPolicyBooks() { require(policyBookRegistry.isPolicyBook(_msgSender()), "BDS: No access"); _; } function __BMICoverStaking_init() external initializer { __Ownable_init(); __ERC1155_init(""); _nftMintId = 1; allowStakeProfit = true; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { bmiToken = IERC20(_contractsRegistry.getBMIContract()); rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); if (allowStakeProfit) { bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract()); } liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); shieldMining = IShieldMining(_contractsRegistry.getShieldMiningContract()); bmiTreasury = _contractsRegistry.getBMITreasury(); } /// @dev the output URI will be: "https://token-cdn-domain/<tokenId>" function uri(uint256 tokenId) public view override(ERC1155Upgradeable, IBMICoverStaking) returns (string memory) { return string(abi.encodePacked(super.uri(0), Strings.toString(tokenId))); } /// @dev this is a correct URI: "https://token-cdn-domain/" function setBaseURI(string calldata newURI) external onlyOwner { _setURI(newURI); } function setAllowStakeProfit(bool _allowStakeProfit) external onlyOwner { allowStakeProfit = _allowStakeProfit; } function recoverTokens() external onlyOwner { uint256 balance = bmiToken.balanceOf(address(this)); bmiToken.transfer(_msgSender(), balance); emit TokensRecovered(_msgSender(), balance); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 1) { // not an NFT continue; } if (from == address(0)) { // mint happened _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); } else if (to == address(0)) { // burn happened _nftHolderTokens[from].remove(ids[i]); _nftTokenOwners.remove(ids[i]); } else { // transfer happened _nftHolderTokens[from].remove(ids[i]); _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); _updateLiquidityRegistry(to, from, _stakersPool[ids[i]].policyBookAddress); } } } function _updateLiquidityRegistry( address to, address from, address policyBookAddress ) internal { liquidityRegistry.tryToAddPolicyBook(to, policyBookAddress); liquidityRegistry.tryToRemovePolicyBook(from, policyBookAddress); } function _mintStake(address staker, uint256 id) internal { _mint(staker, id, 1, ""); // mint NFT } function _burnStake(address staker, uint256 id) internal { _burn(staker, id, 1); // burn NFT } function _mintAggregatedNFT( address staker, address policyBookAddress, uint256[] memory tokenIds ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 totalBMIXAmount; for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == _msgSender(), "BDS: Not a token owner"); require( _stakersPool[tokenIds[i]].policyBookAddress == policyBookAddress, "BDS: NFTs from distinct origins" ); totalBMIXAmount = totalBMIXAmount.add(_stakersPool[tokenIds[i]].stakedBMIXAmount); _burnStake(staker, tokenIds[i]); emit StakingNFTBurned(tokenIds[i], policyBookAddress); /// @dev should be enough delete _stakersPool[tokenIds[i]].policyBookAddress; } _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, totalBMIXAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function _mintNewNFT( address staker, uint256 bmiXAmount, address policyBookAddress ) internal { _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, bmiXAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external override { require(tokenIds.length > 1, "BDS: Can't aggregate"); _mintAggregatedNFT(_msgSender(), policyBookAddress, tokenIds); rewardsGenerator.aggregate(policyBookAddress, tokenIds, _nftMintId - 1); // nftMintId is changed, so -1 } function stakeBMIX(uint256 bmiXAmount, address policyBookAddress) external override { _stakeBMIX(_msgSender(), bmiXAmount, policyBookAddress); } function stakeBMIXWithPermit( uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external override { _stakeBMIXWithPermit(_msgSender(), bmiXAmount, policyBookAddress, v, r, s); } function stakeBMIXFrom(address user, uint256 bmiXAmount) external override onlyPolicyBooks { _stakeBMIX(user, bmiXAmount, _msgSender()); } function stakeBMIXFromWithPermit( address user, uint256 bmiXAmount, uint8 v, bytes32 r, bytes32 s ) external override onlyPolicyBooks { _stakeBMIXWithPermit(user, bmiXAmount, _msgSender(), v, r, s); } function _stakeBMIXWithPermit( address staker, uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) internal { IERC20PermitUpgradeable(policyBookAddress).permit( staker, address(this), bmiXAmount, MAX_INT, v, r, s ); _stakeBMIX(staker, bmiXAmount, policyBookAddress); } function _stakeBMIX( address user, uint256 bmiXAmount, address policyBookAddress ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); require(IPolicyBook(policyBookAddress).whitelisted(), "BDS: PB is not whitelisted"); require(bmiXAmount > 0, "BDS: Zero tokens"); uint256 stblAmount = IPolicyBook(policyBookAddress).convertBMIXToSTBL(bmiXAmount); IERC20(policyBookAddress).transferFrom(user, address(this), bmiXAmount); _mintNewNFT(user, bmiXAmount, policyBookAddress); rewardsGenerator.stake(policyBookAddress, _nftMintId - 1, stblAmount); // nftMintId is changed, so -1 } function _transferProfit(uint256 tokenId, bool onlyProfit) internal { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; uint256 totalProfit; if (onlyProfit) { totalProfit = rewardsGenerator.withdrawReward(policyBookAddress, tokenId); } else { totalProfit = rewardsGenerator.withdrawFunds(policyBookAddress, tokenId); } uint256 bmiStakingProfit = _getSlashed(totalProfit); uint256 profit = totalProfit.sub(bmiStakingProfit); // transfer slashed bmi to the bmi treasury bmiToken.transfer(bmiTreasury, bmiStakingProfit); // transfer bmi profit to the user bmiToken.transfer(_msgSender(), profit); emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit); } /// @param staker address of the staker account /// @param policyBookAddress addres of the policbook /// @param offset pagination start up place /// @param limit size of the listing page /// @param func callback function that returns a uint256 /// @return total function _aggregateForEach( address staker, address policyBookAddress, uint256 offset, uint256 limit, function(uint256) view returns (uint256) func ) internal view returns (uint256 total) { bool nullAddr = policyBookAddress == address(0); require(nullAddr || policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 to = (offset.add(limit)).min(balanceOf(staker)).max(offset); for (uint256 i = offset; i < to; i++) { uint256 nftIndex = tokenOfOwnerByIndex(staker, i); if (nullAddr || _stakersPool[nftIndex].policyBookAddress == policyBookAddress) { total = total.add(func(nftIndex)); } } } function _transferForEach(address policyBookAddress, function(uint256) func) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 stakerBalance = balanceOf(_msgSender()); for (int256 i = int256(stakerBalance) - 1; i >= 0; i--) { uint256 nftIndex = tokenOfOwnerByIndex(_msgSender(), uint256(i)); if (_stakersPool[nftIndex].policyBookAddress == policyBookAddress) { func(nftIndex); } } } function restakeBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); require(allowStakeProfit, "BDS: restake not avaiable"); uint256 totalProfit = rewardsGenerator.withdrawReward(_stakersPool[tokenId].policyBookAddress, tokenId); bmiToken.transfer(address(bmiStaking), totalProfit); bmiStaking.stakeFor(_msgSender(), totalProfit); } function restakeStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, restakeBMIProfit); } function withdrawBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, true); } function withdrawStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawBMIProfit); if (policyBookRegistry.isUserLeveragePool(policyBookAddress)) { shieldMining.getRewardFor(_msgSender(), policyBookAddress); } else { shieldMining.getRewardFor(_msgSender(), policyBookAddress, address(0)); } } function withdrawFundsWithProfit(uint256 tokenId) public override { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; require(policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, false); uint256 stakedFunds = _stakersPool[tokenId].stakedBMIXAmount; // transfer bmiX from staking to the user IERC20(policyBookAddress).transfer(_msgSender(), stakedFunds); emit StakingFundsWithdrawn(tokenId, policyBookAddress, _msgSender(), stakedFunds); _burnStake(_msgSender(), tokenId); emit StakingNFTBurned(tokenId, policyBookAddress); delete _stakersPool[tokenId]; } function withdrawStakerFundsWithProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawFundsWithProfit); } function getSlashedBMIProfit(uint256 tokenId) public view override returns (uint256) { return _applySlashing(getBMIProfit(tokenId)); } /// @notice retrieves the BMI profit of a tokenId /// @param tokenId numeric id identifier of the token /// @return profit amount function getBMIProfit(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getReward(_stakersPool[tokenId].policyBookAddress, tokenId); } function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view override returns (uint256 totalProfit) { uint256 stakerBMIProfit = getStakerBMIProfit(staker, policyBookAddress, offset, limit); return _applySlashing(stakerBMIProfit); } function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) public view override returns (uint256) { return _aggregateForEach(staker, policyBookAddress, offset, limit, getBMIProfit); } function totalStaked(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedByNFT); } function totalStakedSTBL(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedSTBLByNFT); } function stakedByNFT(uint256 tokenId) public view override returns (uint256) { return _stakersPool[tokenId].stakedBMIXAmount; } function stakedSTBLByNFT(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getStakedNFTSTBL(tokenId); } /// @notice returns number of NFTs on user's account function balanceOf(address user) public view override returns (uint256) { return _nftHolderTokens[user].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _nftTokenOwners.get(tokenId); } function tokenOfOwnerByIndex(address user, uint256 index) public view override returns (uint256) { return _nftHolderTokens[user].at(index); } }
returns number of NFTs on user's account
function balanceOf(address user) public view override returns (uint256) { return _nftHolderTokens[user].length(); }
1,056,602
// โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— // โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ // โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–‘โ–‘โ–ˆโ–ˆโ•‘ // โ–ˆโ–ˆโ•”โ•โ•โ•โ–‘โ–‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ–‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ–‘โ–ˆโ–ˆโ•”โ•โ•โ•โ–‘โ–‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•”โ•โ•โ•โ–‘โ–‘โ–ˆโ–ˆโ•‘ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ•‘ // โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ–‘โ–‘โ•šโ•โ•โ•šโ•โ•โ–‘โ–‘โ–‘โ–‘โ–‘โ•šโ•โ•โ–‘โ–‘โ–‘โ–‘โ–‘โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ–‘โ–‘โ•šโ•โ•โ•šโ•โ•โ•šโ•โ•โ–‘โ–‘โ–‘โ–‘โ–‘โ•šโ•โ• // Copyright (C) 2020 zapper, nodar, suhail, seb, sumit, apoorv // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice This contract adds liquidity to Uniswap V2 pools using ETH or any ERC20 Token. // SPDX-License-Identifier: GPLv2 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 ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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" ); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } /** * @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. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address payable public _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address payable 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 payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address payable newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // import "@uniswap/lib/contracts/libraries/Babylonian.sol"; library Babylonian { function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Pair { function token0() external pure returns (address); function token1() external pure returns (address); function getReserves() external view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ); } contract UniswapV2_ZapIn_General_V2_4_1 is ReentrancyGuard, Ownable { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; bool public stopped = false; uint16 public goodwill; address private constant zgoodwillAddress = 0xE737b6AfEC2320f616297e59445b60a11e3eF75F; IUniswapV2Router02 private constant uniswapRouter = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory private constant UniSwapV2FactoryAddress = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); address private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 private constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; constructor(uint16 _goodwill) public { goodwill = _goodwill; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } /** @notice This function is used to invest in given Uniswap V2 pair through ETH/ERC20 Tokens @param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether) @param _ToUnipoolToken0 The Uniswap V2 pair token0 address @param _ToUnipoolToken1 The Uniswap V2 pair token1 address @param _amount The amount of fromToken to invest @param _minPoolTokens Reverts if less tokens received than this @return Amount of LP bought */ function ZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount, uint256 _minPoolTokens ) public payable nonReentrant stopInEmergency returns (uint256) { uint256 toInvest; if (_FromTokenContractAddress == address(0)) { require(msg.value > 0, "Error: ETH not sent"); toInvest = msg.value; } else { require(msg.value == 0, "Error: ETH sent"); require(_amount > 0, "Error: Invalid ERC amount"); IERC20(_FromTokenContractAddress).safeTransferFrom( msg.sender, address(this), _amount ); toInvest = _amount; } uint256 LPBought = _performZapIn( _toWhomToIssue, _FromTokenContractAddress, _ToUnipoolToken0, _ToUnipoolToken1, toInvest ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); //get pair address address _ToUniPoolAddress = UniSwapV2FactoryAddress.getPair( _ToUnipoolToken0, _ToUnipoolToken1 ); //transfer goodwill uint256 goodwillPortion = _transferGoodwill( _ToUniPoolAddress, LPBought ); IERC20(_ToUniPoolAddress).safeTransfer( _toWhomToIssue, SafeMath.sub(LPBought, goodwillPortion) ); return SafeMath.sub(LPBought, goodwillPortion); } function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount ) internal returns (uint256) { address intermediate = _getIntermediate( _FromTokenContractAddress, _amount, _ToUnipoolToken0, _ToUnipoolToken1 ); // swap to intermediate uint256 interAmt = _token2Token( _FromTokenContractAddress, intermediate, _amount ); // divide to swap in amounts uint256 token0Bought; uint256 token1Bought; IUniswapV2Pair pair = IUniswapV2Pair( UniSwapV2FactoryAddress.getPair(_ToUnipoolToken0, _ToUnipoolToken1) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); if (intermediate == _ToUnipoolToken0) { uint256 amountToSwap = calculateSwapInAmount(res0, interAmt); //if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token1Bought = _token2Token( intermediate, _ToUnipoolToken1, amountToSwap ); token0Bought = interAmt.sub(amountToSwap); } else { uint256 amountToSwap = calculateSwapInAmount(res1, interAmt); //if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token0Bought = _token2Token( intermediate, _ToUnipoolToken0, amountToSwap ); token1Bought = interAmt.sub(amountToSwap); } return _uniDeposit( _toWhomToIssue, _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought ); } function _uniDeposit( address _toWhomToIssue, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 token0Bought, uint256 token1Bought ) internal returns (uint256) { IERC20(_ToUnipoolToken0).safeIncreaseAllowance( address(uniswapRouter), token0Bought ); IERC20(_ToUnipoolToken1).safeIncreaseAllowance( address(uniswapRouter), token1Bought ); (uint256 amountA, uint256 amountB, uint256 LP) = uniswapRouter .addLiquidity( _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought, 1, 1, address(this), deadline ); //Returning Residue in token0, if any. if (token0Bought.sub(amountA) > 0) { IERC20(_ToUnipoolToken0).safeTransfer( _toWhomToIssue, token0Bought.sub(amountA) ); } //Returning Residue in token1, if any if (token1Bought.sub(amountB) > 0) { IERC20(_ToUnipoolToken1).safeTransfer( _toWhomToIssue, token1Bought.sub(amountB) ); } return LP; } function _getIntermediate( address _FromTokenContractAddress, uint256 _amount, address _ToUnipoolToken0, address _ToUnipoolToken1 ) internal view returns (address) { // set from to weth for eth input if (_FromTokenContractAddress == address(0)) { _FromTokenContractAddress = wethTokenAddress; } if (_FromTokenContractAddress == _ToUnipoolToken0) { return _ToUnipoolToken0; } else if (_FromTokenContractAddress == _ToUnipoolToken1) { return _ToUnipoolToken1; } else { IUniswapV2Pair pair = IUniswapV2Pair( UniSwapV2FactoryAddress.getPair( _ToUnipoolToken0, _ToUnipoolToken1 ) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); uint256 ratio; bool isToken0Numerator; if (res0 >= res1) { ratio = res0 / res1; isToken0Numerator = true; } else { ratio = res1 / res0; } //find outputs on swap uint256 output0 = _calculateSwapOutput( _FromTokenContractAddress, _amount, _ToUnipoolToken0 ); uint256 output1 = _calculateSwapOutput( _FromTokenContractAddress, _amount, _ToUnipoolToken1 ); if (isToken0Numerator) { if (output1 * ratio >= output0) return _ToUnipoolToken1; else return _ToUnipoolToken0; } else { if (output0 * ratio >= output1) return _ToUnipoolToken0; else return _ToUnipoolToken1; } } } function _calculateSwapOutput( address _from, uint256 _amt, address _to ) internal view returns (uint256) { // check output via tokenA -> tokenB address pairA = UniSwapV2FactoryAddress.getPair(_from, _to); uint256 amtA; if (pairA != address(0)) { address[] memory pathA = new address[](2); pathA[0] = _from; pathA[1] = _to; amtA = uniswapRouter.getAmountsOut(_amt, pathA)[1]; } uint256 amtB; // check output via tokenA -> weth -> tokenB if ((_from != wethTokenAddress) && _to != wethTokenAddress) { address[] memory pathB = new address[](3); pathB[0] = _from; pathB[1] = wethTokenAddress; pathB[2] = _to; amtB = uniswapRouter.getAmountsOut(_amt, pathB)[2]; } if (amtA >= amtB) { return amtA; } else { return amtB; } } function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) public pure returns (uint256) { return Babylonian .sqrt( reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009)) ) .sub(reserveIn.mul(1997)) / 1994; } /** @notice This function is used to swap ETH/ERC20 <> ETH/ERC20 @param _FromTokenContractAddress The token address to swap from. (0x00 for ETH) @param _ToTokenContractAddress The token address to swap to. (0x00 for ETH) @param tokens2Trade The amount of tokens to swap @return tokenBought The quantity of tokens bought */ function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 tokenBought) { if (_FromTokenContractAddress == _ToTokenContractAddress) { return tokens2Trade; } if (_FromTokenContractAddress == address(0)) { if (_ToTokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).deposit.value(tokens2Trade)(); return tokens2Trade; } address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactETHForTokens.value( tokens2Trade )(1, path, address(this), deadline)[path.length - 1]; } else if (_ToTokenContractAddress == address(0)) { if (_FromTokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).withdraw(tokens2Trade); return tokens2Trade; } IERC20(_FromTokenContractAddress).safeIncreaseAllowance( address(uniswapRouter), tokens2Trade ); address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForETH( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } else { IERC20(_FromTokenContractAddress).safeIncreaseAllowance( address(uniswapRouter), tokens2Trade ); if (_FromTokenContractAddress != wethTokenAddress) { if (_ToTokenContractAddress != wethTokenAddress) { // check output via tokenA -> tokenB address pairA = UniSwapV2FactoryAddress.getPair( _FromTokenContractAddress, _ToTokenContractAddress ); address[] memory pathA = new address[](2); pathA[0] = _FromTokenContractAddress; pathA[1] = _ToTokenContractAddress; uint256 amtA; if (pairA != address(0)) { amtA = uniswapRouter.getAmountsOut( tokens2Trade, pathA )[1]; } // check output via tokenA -> weth -> tokenB address[] memory pathB = new address[](3); pathB[0] = _FromTokenContractAddress; pathB[1] = wethTokenAddress; pathB[2] = _ToTokenContractAddress; uint256 amtB = uniswapRouter.getAmountsOut( tokens2Trade, pathB )[2]; if (amtA >= amtB) { tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathA, address(this), deadline )[pathA.length - 1]; } else { tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathB, address(this), deadline )[pathB.length - 1]; } } else { address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } } else { address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } } require(tokenBought > 0, "Error Swapping Tokens"); } /** @notice This function is used to calculate and transfer goodwill @param _tokenContractAddress Token in which goodwill is deducted @param tokens2Trade The total amount of tokens to be zapped in @return The quantity of goodwill deducted */ function _transferGoodwill( address _tokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 goodwillPortion) { goodwillPortion = SafeMath.div( SafeMath.mul(tokens2Trade, goodwill), 10000 ); if (goodwillPortion == 0) { return 0; } IERC20(_tokenContractAddress).safeTransfer( zgoodwillAddress, goodwillPortion ); } function set_new_goodwill(uint16 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill < 10000, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner { uint256 qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(owner(), qty); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } // - to withdraw any ETH balance sitting in the contract function withdraw() public onlyOwner { uint256 contractBalance = address(this).balance; address payable _to = owner().toPayable(); _to.transfer(contractBalance); } function() external payable { require(msg.sender != tx.origin, "Do not send ETH directly"); } }
swap to intermediate divide to swap in amountsif no reserve or a new pair is createdif no reserve or a new pair is created
function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount ) internal returns (uint256) { address intermediate = _getIntermediate( _FromTokenContractAddress, _amount, _ToUnipoolToken0, _ToUnipoolToken1 ); uint256 interAmt = _token2Token( _FromTokenContractAddress, intermediate, _amount ); uint256 token0Bought; uint256 token1Bought; IUniswapV2Pair pair = IUniswapV2Pair( UniSwapV2FactoryAddress.getPair(_ToUnipoolToken0, _ToUnipoolToken1) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); if (intermediate == _ToUnipoolToken0) { uint256 amountToSwap = calculateSwapInAmount(res0, interAmt); if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token1Bought = _token2Token( intermediate, _ToUnipoolToken1, amountToSwap ); token0Bought = interAmt.sub(amountToSwap); uint256 amountToSwap = calculateSwapInAmount(res1, interAmt); if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token0Bought = _token2Token( intermediate, _ToUnipoolToken0, amountToSwap ); token1Bought = interAmt.sub(amountToSwap); } return _uniDeposit( _toWhomToIssue, _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought ); }
7,662,734
./full_match/1/0x85979c90D53E20E4505C83d9408b8A61Beb8db1F/sources/contracts/Aladdin.sol
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./indicates if fee should be deducted from transferif any account belongs to _isExcludedFromFee account then remove the fee
function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool){ uint256 currentAllowance=_allowances[sender][msg.sender]; require(currentAllowance>=amount,"ERC20:transfer amount exceeds allowance"); bool takeFee = true; if(_exludeFromFee[msg.sender] || _exludeFromFee[recipient]){ takeFee = false; } unchecked{ _approve(sender,msg.sender,currentAllowance.sub(amount)); } return true; }
9,732,638
./partial_match/1/0xb9516057dC40C92F91B6EbB2E3d04288cd0446F1/sources/TellorSender.sol
Gets the 5 miners who mined the value for the specified requestId/_timestamp _requestId to looku p _timestamp is the timestamp to look up miners for return bool true if requestId/timestamp is under dispute/
function isInDispute(uint256 _requestId, uint256 _timestamp) public view returns(bool){ return tellor.isInDispute(_requestId, _timestamp); }
2,700,195
./full_match/137/0xE1e46C14F9E400e928b0ead380B98a9309a2307B/sources/contracts/stability-pool-base.sol
to withdraw collateral rewards earned after liquidations this function does not provide an opportunity for a reentrancy attack
function redeemReward() public override { Snapshots memory snapshots = depositSnapshots[msg.sender]; uint256 contributorDeposit = deposits[msg.sender]; uint256 compoundedDeposit = _getCompoundedDepositFromSnapshots(contributorDeposit, snapshots); _redeemReward(); _updateDepositAndSnapshots(msg.sender, compoundedDeposit); }
4,684,673
./partial_match/1/0x242d6E16653b30c830C1918b5Cc23d27253B2d26/sources/ProxyERC20.sol
mock the payload for sendFrom()
function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) public view virtual override returns (uint nativeFee, uint zroFee) { bytes memory payload = abi.encode(PT_SEND, abi.encodePacked(msg.sender), _toAddress, _amount); return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams); }
15,547,706
./partial_match/1/0x04cB5d4d4F2F33380A30C7720A0710e2F22E1D8F/sources/WandBot.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Wand Bot", "WAND") { 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 = 3; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 0; uint256 totalSupply = 100000000000 * 1e18; maxTransactionAmount = (totalSupply * 1) / 100; maxHoldingAmount = (totalSupply * 1) / 100; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x353876E0528De5A6293a6a0780E3e6b826d214Be); devWallet = address(0xD41Bc68606639e73E01e81Db61FBd7CF365DC004); lpWallet = msg.sender; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(marketingWallet, true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,628,561
pragma solidity ^0.4.24; /** * Audited by VZ Chains (vzchains.com) * HashRushICO.sol creates the client's token for crowdsale and allows for subsequent token sales and minting of tokens * Crowdsale contracts edited from original contract code at https://www.ethereum.org/crowdsale#crowdfund-your-idea * Additional crowdsale contracts, functions, libraries from OpenZeppelin * at https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token * Token contract edited from original contract code at https://www.ethereum.org/token * ERC20 interface and certain token functions adapted from https://github.com/ConsenSys/Tokens **/ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { //Sets events and functions for ERC20 token event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } /** * @title Owned * @dev The Owned contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Owned { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } 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; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } 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 sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); uint256 c = a - b; return c; } } contract HashRush is ERC20, Owned { // Applies SafeMath library to uint256 operations using SafeMath for uint256; // Public variables string public name; string public symbol; uint256 public decimals; // Variables uint256 totalSupply_; uint256 multiplier; // Arrays for balances & allowance mapping (address => uint256) balance; mapping (address => mapping (address => uint256)) allowed; // Modifier to prevent short address attack modifier onlyPayloadSize(uint size) { if(msg.data.length < size.add(4)) revert(); _; } constructor(string tokenName, string tokenSymbol, uint8 decimalUnits, uint256 decimalMultiplier) public { name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; multiplier = decimalMultiplier; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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. * @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 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 balance[_owner]; } /** * @dev Transfer token to a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balance[msg.sender]); if ((balance[msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to]) ) { balance[msg.sender] = balance[msg.sender].sub(_value); balance[_to] = balance[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } /** * @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) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to])) { balance[_to] = balance[_to].add(_value); balance[_from] = balance[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } else { return false; } } } contract HashRushICO is Owned, HashRush { // Applies SafeMath library to uint256 operations using SafeMath for uint256; // Public Variables address public multiSigWallet; uint256 public amountRaised; uint256 public startTime; uint256 public stopTime; uint256 public fixedTotalSupply; uint256 public price; uint256 public minimumInvestment; uint256 public crowdsaleTarget; // Variables bool crowdsaleClosed = true; string tokenName = "HashRush"; string tokenSymbol = "RUSH"; uint256 multiplier = 100000000; uint8 decimalUnits = 8; // Initializes the token constructor() HashRush(tokenName, tokenSymbol, decimalUnits, multiplier) public { multiSigWallet = msg.sender; fixedTotalSupply = 70000000; fixedTotalSupply = fixedTotalSupply.mul(multiplier); } /** * @dev Fallback function creates tokens and sends to investor when crowdsale is open */ function () public payable { require(!crowdsaleClosed && (now < stopTime) && (msg.value >= minimumInvestment) && (totalSupply_.add(msg.value.mul(price).mul(multiplier).div(1 ether)) <= fixedTotalSupply) && (amountRaised.add(msg.value.div(1 ether)) <= crowdsaleTarget) ); address recipient = msg.sender; amountRaised = amountRaised.add(msg.value.div(1 ether)); uint256 tokens = msg.value.mul(price).mul(multiplier).div(1 ether); totalSupply_ = totalSupply_.add(tokens); } /** * @dev Function to mint tokens * @param target 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 mintToken(address target, uint256 amount) onlyOwner public returns (bool) { require(amount > 0); require(totalSupply_.add(amount) <= fixedTotalSupply); uint256 addTokens = amount; balance[target] = balance[target].add(addTokens); totalSupply_ = totalSupply_.add(addTokens); emit Transfer(0, target, addTokens); return true; } /** * @dev Function to set token price * @param newPriceperEther New price. * @return A boolean that indicates if the operation was successful. */ function setPrice(uint256 newPriceperEther) onlyOwner public returns (uint256) { require(newPriceperEther > 0); price = newPriceperEther; return price; } /** * @dev Function to set the multisig wallet for a crowdsale * @param wallet Wallet address. * @return A boolean that indicates if the operation was successful. */ function setMultiSigWallet(address wallet) onlyOwner public returns (bool) { multiSigWallet = wallet; return true; } /** * @dev Function to set the minimum investment to participate in crowdsale * @param minimum minimum amount in wei. * @return A boolean that indicates if the operation was successful. */ function setMinimumInvestment(uint256 minimum) onlyOwner public returns (bool) { minimumInvestment = minimum; return true; } /** * @dev Function to set the crowdsale target * @param target Target amount in ETH. * @return A boolean that indicates if the operation was successful. */ function setCrowdsaleTarget(uint256 target) onlyOwner public returns (bool) { crowdsaleTarget = target; return true; } /** * @dev Function to start the crowdsale specifying startTime and stopTime * @param saleStart Sale start timestamp. * @param saleStop Sale stop timestamo. * @param salePrice Token price per ether. * @param setBeneficiary Beneficiary address. * @param minInvestment Minimum investment to participate in crowdsale (wei). * @param saleTarget Crowdsale target in ETH * @return A boolean that indicates if the operation was successful. */ function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) { require(saleStop > now); startTime = saleStart; stopTime = saleStop; amountRaised = 0; crowdsaleClosed = false; setPrice(salePrice); setMultiSigWallet(setBeneficiary); setMinimumInvestment(minInvestment); setCrowdsaleTarget(saleTarget); return true; } /** * @dev Function that allows owner to stop the crowdsale immediately * @return A boolean that indicates if the operation was successful. */ function stopSale() onlyOwner public returns (bool) { stopTime = now; crowdsaleClosed = true; return true; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to])) { balance[_to] = balance[_to].add(_value); balance[_from] = balance[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; return false; } }
14,075,563
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./CVNXGovernance.sol"; import "./ICVNX.sol"; /// @notice CVNX token contract. contract CVNX is ICVNX, ERC20("CVNX", "CVNX"), Ownable { event TokenLocked(uint256 indexed amount, address tokenOwner); event TokenUnlocked(uint256 indexed amount, address tokenOwner); /// @notice Governance contract. CVNXGovernance public cvnxGovernanceContract; IERC20 public cvnContract; /// @notice Locked token amount for each address. mapping(address => uint256) public lockedAmount; /// @notice Governance contract created in constructor. constructor(address _cvnContract) { uint256 _toMint = 6000000000000; _mint(msg.sender, _toMint); approve(address(this), _toMint); cvnContract = IERC20(_cvnContract); cvnxGovernanceContract = new CVNXGovernance(address(this)); cvnxGovernanceContract.transferOwnership(msg.sender); } /// @notice Modifier describe that call available only from governance contract. modifier onlyGovContract() { require(msg.sender == address(cvnxGovernanceContract), "[E-31] - Not a governance contract."); _; } /// @notice Tokens decimal. function decimals() public pure override returns (uint8) { return 5; } /// @notice Lock tokens on holder balance. /// @param _tokenOwner Token holder /// @param _tokenAmount Amount to lock function lock(address _tokenOwner, uint256 _tokenAmount) external override onlyGovContract { require(_tokenAmount > 0, "[E-41] - The amount to be locked must be greater than zero."); uint256 _balance = balanceOf(_tokenOwner); uint256 _toLock = lockedAmount[_tokenOwner] + _tokenAmount; require(_toLock <= _balance, "[E-42] - Not enough token on account."); lockedAmount[_tokenOwner] = _toLock; emit TokenLocked(_tokenAmount, _tokenOwner); } /// @notice Unlock tokens on holder balance. /// @param _tokenOwner Token holder /// @param _tokenAmount Amount to lock function unlock(address _tokenOwner, uint256 _tokenAmount) external override onlyGovContract { uint256 _lockedAmount = lockedAmount[_tokenOwner]; if (_tokenAmount > _lockedAmount) { _tokenAmount = _lockedAmount; } lockedAmount[_tokenOwner] = _lockedAmount - _tokenAmount; emit TokenUnlocked(_tokenAmount, _tokenOwner); } /// @notice Swap CVN to CVNX tokens /// @param _amount Token amount to swap function swap(uint256 _amount) external override returns (bool) { cvnContract.transferFrom(msg.sender, 0x4e07dc9D1aBCf1335d1EaF4B2e28b45d5892758E, _amount); this.transferFrom(owner(), msg.sender, _amount); return true; } /// @notice Transfer stuck tokens /// @param _token Token contract address /// @param _to Receiver address /// @param _amount Token amount function transferStuckERC20( IERC20 _token, address _to, uint256 _amount ) external override onlyOwner { require(_token.transfer(_to, _amount), "[E-56] - Transfer failed."); } /// @notice Check that locked amount less then transfer amount function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal view override { if (_from != address(0)) { require( balanceOf(_from) - lockedAmount[_from] >= _amount, "[E-61] - Transfer amount exceeds available tokens." ); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./CVNX.sol"; import "./ICVNXGovernance.sol"; /// @notice Governance contract for CVNX token. contract CVNXGovernance is ICVNXGovernance, Ownable { CVNX private cvnx; /// @notice Emit when new poll created. event PollCreated(uint256 indexed pollNum); /// @notice Emit when address vote in poll. event PollVoted(address voterAddress, VoteType indexed voteType, uint256 indexed voteWeight); /// @notice Emit when poll stopped. event PollStop(uint256 indexed pollNum, uint256 indexed stopTimestamp); /// @notice Contain all polls. Index - poll number. Poll[] public polls; /// @notice Contain Vote for addresses that vote in poll. mapping(uint256 => mapping(address => Vote)) public voted; /// @notice Shows whether tokens are locked for a certain pool at a certain address. mapping(uint256 => mapping(address => bool)) public isTokenLockedInPoll; /// @notice List of verified addresses for PRIVATE poll. mapping(uint256 => mapping(address => bool)) public verifiedToVote; /// @param _cvnxTokenAddress CVNX token address. constructor(address _cvnxTokenAddress) { cvnx = CVNX(_cvnxTokenAddress); } /// @notice Modifier check minimal CVNX token balance before method call. /// @param _minimalBalance Minimal balance on address (Wei) modifier onlyWithBalanceNoLess(uint256 _minimalBalance) { require(cvnx.balanceOf(msg.sender) > _minimalBalance, "[E-34] - Your balance is too low."); _; } /// @notice Create PROPOSAL poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createProposalPoll(uint64 _pollDeadline, string memory _pollInfo) external override { _createPoll(PollType.PROPOSAL, _pollDeadline, _pollInfo); } /// @notice Create EXECUTIVE poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createExecutivePoll(uint64 _pollDeadline, string memory _pollInfo) external override onlyOwner { _createPoll(PollType.EXECUTIVE, _pollDeadline, _pollInfo); } /// @notice Create EVENT poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createEventPoll(uint64 _pollDeadline, string memory _pollInfo) external override onlyOwner { _createPoll(PollType.EVENT, _pollDeadline, _pollInfo); } /// @notice Create PRIVATE poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll /// @param _verifiedAddresses Array of verified addresses for poll function createPrivatePoll( uint64 _pollDeadline, string memory _pollInfo, address[] memory _verifiedAddresses ) external override onlyOwner { uint256 _verifiedAddressesCount = _verifiedAddresses.length; require(_verifiedAddressesCount > 1, "[E-35] - Verified addresses not set."); uint256 _pollNum = _createPoll(PollType.PRIVATE, _pollDeadline, _pollInfo); for (uint256 i = 0; i < _verifiedAddressesCount; i++) { verifiedToVote[_pollNum][_verifiedAddresses[i]] = true; } } /// @notice Send tokens as vote in poll. Tokens will be lock. /// @param _pollNum Poll number /// @param _voteType Vote type (FOR, AGAINST) /// @param _voteWeight Vote weight in CVNX tokens function vote( uint256 _pollNum, VoteType _voteType, uint256 _voteWeight ) external override onlyWithBalanceNoLess(1000000) { require(polls[_pollNum].pollStopped > block.timestamp, "[E-37] - Poll ended."); if (polls[_pollNum].pollType == PollType.PRIVATE) { require(verifiedToVote[_pollNum][msg.sender] == true, "[E-38] - You are not verify to vote in this poll."); } // Lock tokens cvnx.lock(msg.sender, _voteWeight); isTokenLockedInPoll[_pollNum][msg.sender] = true; uint256 _voterVoteWeightBefore = voted[_pollNum][msg.sender].voteWeight; // Set vote type if (_voterVoteWeightBefore > 0) { require( voted[_pollNum][msg.sender].voteType == _voteType, "[E-39] - The voice type does not match the first one." ); } else { voted[_pollNum][msg.sender].voteType = _voteType; } // Increase vote weight for voter voted[_pollNum][msg.sender].voteWeight = _voterVoteWeightBefore + _voteWeight; // Increase vote weight in poll if (_voteType == VoteType.FOR) { polls[_pollNum].forWeight += _voteWeight; } else { polls[_pollNum].againstWeight += _voteWeight; } emit PollVoted(msg.sender, _voteType, _voteWeight); } /// @notice Unlock tokens for poll. Poll should be ended. /// @param _pollNum Poll number function unlockTokensInPoll(uint256 _pollNum) external override { require(polls[_pollNum].pollStopped <= block.timestamp, "[E-81] - Poll is not ended."); require(isTokenLockedInPoll[_pollNum][msg.sender] == true, "[E-82] - Tokens not locked for this poll."); isTokenLockedInPoll[_pollNum][msg.sender] = false; // Unlock tokens cvnx.unlock(msg.sender, voted[_pollNum][msg.sender].voteWeight); } /// @notice Stop poll before deadline. /// @param _pollNum Poll number function stopPoll(uint256 _pollNum) external override { require( owner() == msg.sender || polls[_pollNum].pollOwner == msg.sender, "[E-91] - Not a contract or poll owner." ); require(block.timestamp < polls[_pollNum].pollDeadline, "[E-92] - Poll ended."); polls[_pollNum].pollStopped = uint64(block.timestamp); emit PollStop(_pollNum, block.timestamp); } /// @notice Return poll status (PENDING, APPROVED, REJECTED, DRAW). /// @param _pollNum Poll number /// @return Poll number and status function getPollStatus(uint256 _pollNum) external view override returns (uint256, PollStatus) { if (polls[_pollNum].pollStopped > block.timestamp) { return (_pollNum, PollStatus.PENDING); } uint256 _forWeight = polls[_pollNum].forWeight; uint256 _againstWeight = polls[_pollNum].againstWeight; if (_forWeight > _againstWeight) { return (_pollNum, PollStatus.APPROVED); } else if (_forWeight < _againstWeight) { return (_pollNum, PollStatus.REJECTED); } else { return (_pollNum, PollStatus.DRAW); } } /// @notice Return the poll expiration timestamp. /// @param _pollNum Poll number /// @return Poll deadline function getPollExpirationTime(uint256 _pollNum) external view override returns (uint64) { return polls[_pollNum].pollDeadline; } /// @notice Return the poll stop timestamp. /// @param _pollNum Poll number /// @return Poll stop time function getPollStopTime(uint256 _pollNum) external view override returns (uint64) { return polls[_pollNum].pollStopped; } /// @notice Return the complete list of polls an address has voted in. /// @param _voter Voter address /// @return Index - poll number. True - if address voted in poll function getPollHistory(address _voter) external view override returns (bool[] memory) { uint256 _pollsCount = polls.length; bool[] memory _pollNums = new bool[](_pollsCount); for (uint256 i = 0; i < _pollsCount; i++) { if (voted[i][_voter].voteWeight > 0) { _pollNums[i] = true; } } return _pollNums; } /// @notice Return the vote info for a given poll for an address. /// @param _pollNum Poll number /// @param _voter Voter address /// @return Info about voter vote function getPollInfoForVoter(uint256 _pollNum, address _voter) external view override returns (Vote memory) { return voted[_pollNum][_voter]; } /// @notice Checks if a user address has voted for a specific poll. /// @param _pollNum Poll number /// @param _voter Voter address /// @return True if address voted in poll function getIfUserHasVoted(uint256 _pollNum, address _voter) external view override returns (bool) { return voted[_pollNum][_voter].voteWeight > 0; } /// @notice Return the amount of tokens that are locked for a given voter address. /// @param _voter Voter address /// @return Poll number function getLockedAmount(address _voter) external view override returns (uint256) { return cvnx.lockedAmount(_voter); } /// @notice Return the amount of locked tokens of the specific poll. /// @param _pollNum Poll number /// @param _voter Voter address /// @return Locked tokens amount for specific poll function getPollLockedAmount(uint256 _pollNum, address _voter) external view override returns (uint256) { if (isTokenLockedInPoll[_pollNum][_voter]) { return voted[_pollNum][_voter].voteWeight; } else { return 0; } } /// @notice Create poll process. /// @param _pollType Poll type /// @param _pollDeadline Poll deadline adn stop timestamp /// @param _pollInfo Poll info /// @return Poll number function _createPoll( PollType _pollType, uint64 _pollDeadline, string memory _pollInfo ) private onlyWithBalanceNoLess(0) returns (uint256) { require(_pollDeadline > block.timestamp, "[E-41] - The deadline must be longer than the current time."); Poll memory _poll = Poll(_pollDeadline, _pollDeadline, _pollType, msg.sender, _pollInfo, 0, 0); uint256 _pollNum = polls.length; polls.push(_poll); emit PollCreated(_pollNum); return _pollNum; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @notice ICVNX interface for CVNX contract. interface ICVNX is IERC20 { /// @notice Lock tokens on holder balance. /// @param _tokenOwner Token holder /// @param _tokenAmount Amount to lock function lock(address _tokenOwner, uint256 _tokenAmount) external; /// @notice Unlock tokens on holder balance. /// @param _tokenOwner Token holder /// @param _tokenAmount Amount to lock function unlock(address _tokenOwner, uint256 _tokenAmount) external; /// @notice Swap CVN to CVNX tokens /// @param _amount Token amount to swap function swap(uint256 _amount) external returns (bool); /// @notice Transfer stuck tokens /// @param _token Token contract address /// @param _to Receiver address /// @param _amount Token amount function transferStuckERC20( IERC20 _token, address _to, uint256 _amount ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; /// @notice ICVNXGovernance interface for CVNXGovernance contract. interface ICVNXGovernance { enum PollType {PROPOSAL, EXECUTIVE, EVENT, PRIVATE} enum PollStatus {PENDING, APPROVED, REJECTED, DRAW} enum VoteType {FOR, AGAINST} /// @notice Poll structure. struct Poll { uint64 pollDeadline; uint64 pollStopped; PollType pollType; address pollOwner; string pollInfo; uint256 forWeight; uint256 againstWeight; } /// @notice Address vote structure. struct Vote { VoteType voteType; uint256 voteWeight; } /// @notice Create PROPOSAL poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createProposalPoll(uint64 _pollDeadline, string memory _pollInfo) external; /// @notice Create EXECUTIVE poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createExecutivePoll(uint64 _pollDeadline, string memory _pollInfo) external; /// @notice Create EVENT poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll function createEventPoll(uint64 _pollDeadline, string memory _pollInfo) external; /// @notice Create PRIVATE poll. /// @param _pollDeadline Poll deadline /// @param _pollInfo Info about poll /// @param _verifiedAddresses Array of verified addresses for poll function createPrivatePoll( uint64 _pollDeadline, string memory _pollInfo, address[] memory _verifiedAddresses ) external; /// @notice Send tokens as vote in poll. Tokens will be lock. /// @param _pollNum Poll number /// @param _voteType Vote type (FOR, AGAINST) /// @param _voteWeight Vote weight in CVNX tokens function vote( uint256 _pollNum, VoteType _voteType, uint256 _voteWeight ) external; /// @notice Unlock tokens for poll. Poll should be ended. /// @param _pollNum Poll number function unlockTokensInPoll(uint256 _pollNum) external; /// @notice Stop poll before deadline. /// @param _pollNum Poll number function stopPoll(uint256 _pollNum) external; /// @notice Return poll status (PENDING, APPROVED, REJECTED, DRAW). /// @param _pollNum Poll number /// @return Poll number and status function getPollStatus(uint256 _pollNum) external view returns (uint256, PollStatus); /// @notice Return the poll expiration timestamp. /// @param _pollNum Poll number /// @return Poll deadline function getPollExpirationTime(uint256 _pollNum) external view returns (uint64); /// @notice Return the poll stop timestamp. /// @param _pollNum Poll number /// @return Poll stop time function getPollStopTime(uint256 _pollNum) external view returns (uint64); /// @notice Return the complete list of polls an address has voted in. /// @param _voter Voter address /// @return Index - poll number. True - if address voted in poll function getPollHistory(address _voter) external view returns (bool[] memory); /// @notice Return the vote info for a given poll for an address. /// @param _pollNum Poll number /// @param _voter Voter address /// @return Info about voter vote function getPollInfoForVoter(uint256 _pollNum, address _voter) external view returns (Vote memory); /// @notice Checks if a user address has voted for a specific poll. /// @param _pollNum Poll number /// @param _voter Voter address /// @return True if address voted in poll function getIfUserHasVoted(uint256 _pollNum, address _voter) external view returns (bool); /// @notice Return the amount of tokens that are locked for a given voter address. /// @param _voter Voter address /// @return Poll number function getLockedAmount(address _voter) external view returns (uint256); /// @notice Return the amount of locked tokens of the specific poll. /// @param _pollNum Poll number /// @param _voter Voter address /// @return Locked tokens amount for specific poll function getPollLockedAmount(uint256 _pollNum, address _voter) external view returns (uint256); } // 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; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Checks if a user address has voted for a specific poll. _pollNum Poll number _voter Voter address return True if address voted in poll
function getIfUserHasVoted(uint256 _pollNum, address _voter) external view override returns (bool) { return voted[_pollNum][_voter].voteWeight > 0; }
367,356
./partial_match/1/0xB74430E51604957b47D010a20bB78f09Cd4E4330/sources/Gou.sol
maxTransactionAmount exclude from paying fees or having max transaction amount
constructor() ERC20("Gou", "GOU") { 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 = 4; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 98; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e6 * 1e18; maxTransactionAmount = 1000000000000000000000000; maxWallet = 20000000000000000000000; swapTokensAtAmount = totalSupply * 10 / 2500; 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);
9,177,182
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./SlasherUtil.sol"; contract DowntimeSlasher is SlasherUtil { using SafeMath for uint256; // For each address, associate each epoch with the last block that was slashed on that epoch mapping(address => mapping(uint256 => uint256)) lastSlashedBlock; uint256 public slashableDowntime; event SlashableDowntimeSet(uint256 interval); /** * @notice Initializer * @param registryAddress Sets the registry address. Useful for testing. * @param _penalty Penalty for the slashed signer. * @param _reward Reward that the observer gets. * @param _slashableDowntime Slashable downtime in blocks. */ function initialize( address registryAddress, uint256 _penalty, uint256 _reward, uint256 _slashableDowntime ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setSlashingIncentives(_penalty, _reward); setSlashableDowntime(_slashableDowntime); } /** * @notice Sets the slashable downtime * @param interval Slashable downtime in blocks. */ function setSlashableDowntime(uint256 interval) public onlyOwner { require(interval != 0, "Slashable downtime cannot be zero"); require(interval < getEpochSize(), "Slashable downtime must be smaller than epoch size"); slashableDowntime = interval; emit SlashableDowntimeSet(interval); } function epochNumberOfBlock(uint256 blockNumber, uint256 epochSize) internal pure returns (uint256) { return blockNumber.add(epochSize).sub(1) / epochSize; } /** * @notice Test if a validator has been down. * @param startBlock First block of the downtime. * @param startSignerIndex Validator index at the first block. * @param endSignerIndex Validator index at the last block. */ function isDown(uint256 startBlock, uint256 startSignerIndex, uint256 endSignerIndex) public view returns (bool) { uint256 endBlock = getEndBlock(startBlock); require(endBlock < block.number - 1, "end block must be smaller than current block"); require( startSignerIndex < numberValidatorsInSet(startBlock), "Bad validator index at start block" ); require(endSignerIndex < numberValidatorsInSet(endBlock), "Bad validator index at end block"); address startSigner = validatorSignerAddressFromSet(startSignerIndex, startBlock); address endSigner = validatorSignerAddressFromSet(endSignerIndex, endBlock); IAccounts accounts = getAccounts(); require( accounts.signerToAccount(startSigner) == accounts.signerToAccount(endSigner), "Signers do not match" ); uint256 sz = getEpochSize(); uint256 startEpoch = epochNumberOfBlock(startBlock, sz); for (uint256 n = startBlock; n <= endBlock; n++) { uint256 signerIndex = epochNumberOfBlock(n, sz) == startEpoch ? startSignerIndex : endSignerIndex; // We want to check signers for block n, // so we get the parent seal bitmap for the next block if (uint256(getParentSealBitmap(n + 1)) & (1 << signerIndex) != 0) return false; } return true; } /** * @notice Returns the end block for the interval. */ function getEndBlock(uint256 startBlock) internal view returns (uint256) { return startBlock + slashableDowntime - 1; } function checkIfAlreadySlashed(address validator, uint256 startBlock) internal { uint256 endBlock = getEndBlock(startBlock); uint256 startEpoch = getEpochNumberOfBlock(startBlock); uint256 endEpoch = getEpochNumberOfBlock(endBlock); require(lastSlashedBlock[validator][startEpoch] < startBlock, "Already slashed"); require(lastSlashedBlock[validator][endEpoch] < startBlock, "Already slashed"); lastSlashedBlock[validator][startEpoch] = endBlock; lastSlashedBlock[validator][endEpoch] = endBlock; } /** * @notice Requires that `isDown` returns true and that the account corresponding to * `signer` has not already been slashed for downtime for the epoch * corresponding to `startBlock`. * If so, fetches the `account` associated with `signer` and the group that * `signer` was a member of during the corresponding epoch. * Then, calls `LockedGold.slash` on both the validator and group accounts. * Calls `Validators.removeSlashedMember` to remove the validator from its * current group if it is a member of one. * Finally, stores that (account, epochNumber) has been slashed. * @param startBlock First block of the downtime. * @param startSignerIndex Validator index at the first block. * @param endSignerIndex Validator index at the last block. * @param groupMembershipHistoryIndex Group membership index from where * the group should be found. (For start block) * @param validatorElectionLessers Lesser pointers for validator slashing. * @param validatorElectionGreaters Greater pointers for validator slashing. * @param validatorElectionIndices Vote indices for validator slashing. * @param groupElectionLessers Lesser pointers for group slashing. * @param groupElectionGreaters Greater pointers for group slashing. * @param groupElectionIndices Vote indices for group slashing. */ function slash( uint256 startBlock, uint256 startSignerIndex, uint256 endSignerIndex, uint256 groupMembershipHistoryIndex, address[] memory validatorElectionLessers, address[] memory validatorElectionGreaters, uint256[] memory validatorElectionIndices, address[] memory groupElectionLessers, address[] memory groupElectionGreaters, uint256[] memory groupElectionIndices ) public { address validator = getAccounts().signerToAccount( validatorSignerAddressFromSet(startSignerIndex, startBlock) ); checkIfAlreadySlashed(validator, startBlock); require(isDown(startBlock, startSignerIndex, endSignerIndex), "Not down"); performSlashing( validator, msg.sender, startBlock, groupMembershipHistoryIndex, validatorElectionLessers, validatorElectionGreaters, validatorElectionIndices, groupElectionLessers, groupElectionGreaters, groupElectionIndices ); } }
Test if a validator has been down. startBlock First block of the downtime. startSignerIndex Validator index at the first block. endSignerIndex Validator index at the last block./ We want to check signers for block n, so we get the parent seal bitmap for the next block
function isDown(uint256 startBlock, uint256 startSignerIndex, uint256 endSignerIndex) public view returns (bool) { uint256 endBlock = getEndBlock(startBlock); require(endBlock < block.number - 1, "end block must be smaller than current block"); require( startSignerIndex < numberValidatorsInSet(startBlock), "Bad validator index at start block" ); require(endSignerIndex < numberValidatorsInSet(endBlock), "Bad validator index at end block"); address startSigner = validatorSignerAddressFromSet(startSignerIndex, startBlock); address endSigner = validatorSignerAddressFromSet(endSignerIndex, endBlock); IAccounts accounts = getAccounts(); require( accounts.signerToAccount(startSigner) == accounts.signerToAccount(endSigner), "Signers do not match" ); uint256 sz = getEpochSize(); uint256 startEpoch = epochNumberOfBlock(startBlock, sz); for (uint256 n = startBlock; n <= endBlock; n++) { uint256 signerIndex = epochNumberOfBlock(n, sz) == startEpoch ? startSignerIndex : endSignerIndex; if (uint256(getParentSealBitmap(n + 1)) & (1 << signerIndex) != 0) return false; } return true; }
1,820,930
// SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IAuthorizer.sol"; import "./interfaces/IWETH.sol"; import "./VaultAuthorization.sol"; import "./FlashLoans.sol"; import "./Swaps.sol"; /** * @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the * entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset * Managers who withdraw and deposit tokens. * * The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making * understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only * the full `Vault` is meant to be deployed. * * Roughly speaking, these are the contents of each sub-contract: * * - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions. * - `Fees`: set and compute protocol fees. * - `FlashLoans`: flash loan transfers and fees. * - `PoolBalances`: Pool joins and exits. * - `PoolRegistry`: Pool registration, ID management, and basic queries. * - `PoolTokens`: Pool token registration and registration, and balance queries. * - `Swaps`: Pool swaps. * - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers) * - `VaultAuthorization`: access control, relayers and signature validation. * * Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`, * `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the * `BalanceAllocation` library. * * The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a * multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as * the different Pool specialization settings. * * Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding * the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code * was required to improve code generation and bring the bytecode size below this limit. This includes extensive * utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated * storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few. */ contract Vault is VaultAuthorization, FlashLoans, Swaps { constructor( IAuthorizer authorizer, IWETH weth, uint256 pauseWindowDuration, uint256 bufferPeriodDuration ) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { // solhint-disable-previous-line no-empty-blocks } function setPaused(bool paused) external override nonReentrant authenticate { _setPaused(paused); } // solhint-disable-next-line func-name-mixedcase function WETH() external view override returns (IWETH) { return _WETH(); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/SignaturesValidator.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation. * * Additionally handles relayer access and approval. */ abstract contract VaultAuthorization is IVault, ReentrancyGuard, Authentication, SignaturesValidator, TemporarilyPausable { // Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but // unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead. // _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58; // _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353; // _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe; // _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a; // _SET_RELAYER_TYPE_HASH = // keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a; IAuthorizer private _authorizer; mapping(address => mapping(address => bool)) private _approvedRelayers; /** * @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that * is, it is a relayer for that function), and either: * a) `user` approved the caller as a relayer (via `setRelayerApproval`), or * b) a valid signature from them was appended to the calldata. * * Should only be applied to external functions. */ modifier authenticateFor(address user) { _authenticateFor(user); _; } constructor(IAuthorizer authorizer) // The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers. Authentication(bytes32(uint256(address(this)))) SignaturesValidator("Balancer V2 Vault") { _setAuthorizer(authorizer); } function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate { _setAuthorizer(newAuthorizer); } function _setAuthorizer(IAuthorizer newAuthorizer) private { emit AuthorizerChanged(newAuthorizer); _authorizer = newAuthorizer; } function getAuthorizer() external view override returns (IAuthorizer) { return _authorizer; } function setRelayerApproval( address sender, address relayer, bool approved ) external override nonReentrant whenNotPaused authenticateFor(sender) { _approvedRelayers[sender][relayer] = approved; emit RelayerApprovalChanged(relayer, sender, approved); } function hasApprovedRelayer(address user, address relayer) external view override returns (bool) { return _hasApprovedRelayer(user, relayer); } /** * @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point * function (that is, it is a relayer for that function) and either: * a) `user` approved the caller as a relayer (via `setRelayerApproval`), or * b) a valid signature from them was appended to the calldata. */ function _authenticateFor(address user) internal { if (msg.sender != user) { // In this context, 'permission to call a function' means 'being a relayer for a function'. _authenticateCaller(); // Being a relayer is not sufficient: `user` must have also approved the caller either via // `setRelayerApproval`, or by providing a signature appended to the calldata. if (!_hasApprovedRelayer(user, msg.sender)) { _validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER); } } } /** * @dev Returns true if `user` approved `relayer` to act as a relayer for them. */ function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) { return _approvedRelayers[user][relayer]; } function _canPerform(bytes32 actionId, address user) internal view override returns (bool) { // Access control is delegated to the Authorizer. return _authorizer.canPerform(actionId, user, address(this)); } function _typeHash() internal pure override returns (bytes32 hash) { // This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the // assembly implementation results in much denser bytecode. // solhint-disable-next-line no-inline-assembly assembly { // The function selector is located at the first 4 bytes of calldata. We copy the first full calldata // 256 word, and then perform a logical shift to the right, moving the selector to the least significant // 4 bytes. let selector := shr(224, calldataload(0)) // With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros, // resulting in dense bytecode (PUSH4 opcodes). switch selector case 0xb95cac28 { hash := _JOIN_TYPE_HASH } case 0x8bdb3913 { hash := _EXIT_TYPE_HASH } case 0x52bbbe29 { hash := _SWAP_TYPE_HASH } case 0x945bcec9 { hash := _BATCH_SWAP_TYPE_HASH } case 0xfa6e671d { hash := _SET_RELAYER_TYPE_HASH } default { hash := 0x0000000000000000000000000000000000000000000000000000000000000000 } } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. // This flash loan provider was based on the Aave protocol's open source // implementation and terminology and interfaces are intentionally kept // similar pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./Fees.sol"; import "./interfaces/IFlashLoanRecipient.sol"; /** * @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient * contract, which implements the `IFlashLoanRecipient` interface. */ abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable { using SafeERC20 for IERC20; function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external override nonReentrant whenNotPaused { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); uint256[] memory feeAmounts = new uint256[](tokens.length); uint256[] memory preLoanBalances = new uint256[](tokens.length); // Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness. IERC20 previousToken = IERC20(0); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; _require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS); previousToken = token; preLoanBalances[i] = token.balanceOf(address(this)); feeAmounts[i] = _calculateFlashLoanFeeAmount(amount); _require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE); token.safeTransfer(address(recipient), amount); } recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 preLoanBalance = preLoanBalances[i]; // Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results // in more accurate revert reasons if the flash loan protocol fee percentage is zero. uint256 postLoanBalance = token.balanceOf(address(this)); _require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE); // No need for checked arithmetic since we know the loan was fully repaid. uint256 receivedFeeAmount = postLoanBalance - preLoanBalance; _require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT); _payFeeAmount(token, receivedFeeAmount); emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/EnumerableMap.sol"; import "../lib/openzeppelin/EnumerableSet.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeCast.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./PoolBalances.sol"; import "./interfaces/IPoolSwapStructs.sol"; import "./interfaces/IGeneralPool.sol"; import "./interfaces/IMinimalSwapInfoPool.sol"; import "./balances/BalanceAllocation.sol"; /** * Implements the Vault's high-level swap functionality. * * Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool * contracts to do this: all security checks are made by the Vault. * * The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. * In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), * and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). * More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together * individual swaps. */ abstract contract Swaps is ReentrancyGuard, PoolBalances { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableMap for EnumerableMap.IERC20ToBytes32Map; using Math for int256; using Math for uint256; using SafeCast for uint256; using BalanceAllocation for bytes32; function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable override nonReentrant whenNotPaused authenticateFor(funds.sender) returns (uint256 amountCalculated) { // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.SWAP_DEADLINE); // This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function // would result in this error. _require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP); IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn); IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut); _require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN); // Initializing each struct field one-by-one uses less gas than setting all at once. IPoolSwapStructs.SwapRequest memory poolRequest; poolRequest.poolId = singleSwap.poolId; poolRequest.kind = singleSwap.kind; poolRequest.tokenIn = tokenIn; poolRequest.tokenOut = tokenOut; poolRequest.amount = singleSwap.amount; poolRequest.userData = singleSwap.userData; poolRequest.from = funds.sender; poolRequest.to = funds.recipient; // The lastChangeBlock field is left uninitialized. uint256 amountIn; uint256 amountOut; (amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest); _require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT); _receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance); _sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance); // If the asset in is ETH, then `amountIn` ETH was wrapped into WETH. _handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0); } function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable override nonReentrant whenNotPaused authenticateFor(funds.sender) returns (int256[] memory assetDeltas) { // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.SWAP_DEADLINE); InputHelpers.ensureInputLengthMatch(assets.length, limits.length); // Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas. assetDeltas = _swapWithPools(swaps, assets, funds, kind); // Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient // (for negative deltas). uint256 wrappedEth = 0; for (uint256 i = 0; i < assets.length; ++i) { IAsset asset = assets[i]; int256 delta = assetDeltas[i]; _require(delta <= limits[i], Errors.SWAP_LIMIT); if (delta > 0) { uint256 toReceive = uint256(delta); _receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(toReceive); } } else if (delta < 0) { uint256 toSend = uint256(-delta); _sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance); } } // Handle any used and remaining ETH. _handleRemainingEth(wrappedEth); } // For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount // (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request). /** * @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose * amount is supplied by the caller). */ function _tokenGiven( SwapKind kind, IERC20 tokenIn, IERC20 tokenOut ) private pure returns (IERC20) { return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut; } /** * @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose * amount is calculated by the Pool). */ function _tokenCalculated( SwapKind kind, IERC20 tokenIn, IERC20 tokenOut ) private pure returns (IERC20) { return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn; } /** * @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind. */ function _getAmounts( SwapKind kind, uint256 amountGiven, uint256 amountCalculated ) private pure returns (uint256 amountIn, uint256 amountOut) { if (kind == SwapKind.GIVEN_IN) { (amountIn, amountOut) = (amountGiven, amountCalculated); } else { // SwapKind.GIVEN_OUT (amountIn, amountOut) = (amountCalculated, amountGiven); } } /** * @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause * any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive * tokens, and negative if it should send them. */ function _swapWithPools( BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, SwapKind kind ) private returns (int256[] memory assetDeltas) { assetDeltas = new int256[](assets.length); // These variables could be declared inside the loop, but that causes the compiler to allocate memory on each // loop iteration, increasing gas costs. BatchSwapStep memory batchSwapStep; IPoolSwapStructs.SwapRequest memory poolRequest; // These store data about the previous swap here to implement multihop logic across swaps. IERC20 previousTokenCalculated; uint256 previousAmountCalculated; for (uint256 i = 0; i < swaps.length; ++i) { batchSwapStep = swaps[i]; bool withinBounds = batchSwapStep.assetInIndex < assets.length && batchSwapStep.assetOutIndex < assets.length; _require(withinBounds, Errors.OUT_OF_BOUNDS); IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]); IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]); _require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN); // Sentinel value for multihop logic if (batchSwapStep.amount == 0) { // When the amount given is zero, we use the calculated amount for the previous swap, as long as the // current swap's given token is the previous calculated token. This makes it possible to swap a // given amount of token A for token B, and then use the resulting token B amount to swap for token C. _require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP); bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut); _require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP); batchSwapStep.amount = previousAmountCalculated; } // Initializing each struct field one-by-one uses less gas than setting all at once poolRequest.poolId = batchSwapStep.poolId; poolRequest.kind = kind; poolRequest.tokenIn = tokenIn; poolRequest.tokenOut = tokenOut; poolRequest.amount = batchSwapStep.amount; poolRequest.userData = batchSwapStep.userData; poolRequest.from = funds.sender; poolRequest.to = funds.recipient; // The lastChangeBlock field is left uninitialized uint256 amountIn; uint256 amountOut; (previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest); previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut); // Accumulate Vault deltas across swaps assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256()); assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub( amountOut.toInt256() ); } } /** * @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and * updating the Pool's balance. * * Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind. */ function _swapWithPool(IPoolSwapStructs.SwapRequest memory request) private returns ( uint256 amountCalculated, uint256 amountIn, uint256 amountOut ) { // Get the calculated amount from the Pool and update its balances address pool = _getPoolAddress(request.poolId); PoolSpecialization specialization = _getPoolSpecialization(request.poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool)); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool)); } else { // PoolSpecialization.GENERAL amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool)); } (amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut); } function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool) private returns (uint256 amountCalculated) { // For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are // stored internally, instead of using getters and setters for all operations. ( bytes32 tokenABalance, bytes32 tokenBBalance, TwoTokenPoolBalances storage poolBalances ) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut); // We have the two Pool balances, but we don't know which one is 'token in' or 'token out'. bytes32 tokenInBalance; bytes32 tokenOutBalance; // In Two Token Pools, token A has a smaller address than token B if (request.tokenIn < request.tokenOut) { // in is A, out is B tokenInBalance = tokenABalance; tokenOutBalance = tokenBBalance; } else { // in is B, out is A tokenOutBalance = tokenABalance; tokenInBalance = tokenBBalance; } // Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap (tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook( request, pool, tokenInBalance, tokenOutBalance ); // We check the token ordering again to create the new shared cash packed struct poolBalances.sharedCash = request.tokenIn < request.tokenOut ? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B : BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A } function _processMinimalSwapInfoPoolSwapRequest( IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool ) private returns (uint256 amountCalculated) { bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn); bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut); // Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap (tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook( request, pool, tokenInBalance, tokenOutBalance ); _minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance; _minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance; } /** * @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token * Pools do this. */ function _callMinimalSwapInfoPoolOnSwapHook( IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool, bytes32 tokenInBalance, bytes32 tokenOutBalance ) internal returns ( bytes32 newTokenInBalance, bytes32 newTokenOutBalance, uint256 amountCalculated ) { uint256 tokenInTotal = tokenInBalance.total(); uint256 tokenOutTotal = tokenOutBalance.total(); request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock()); // Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal); (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); newTokenInBalance = tokenInBalance.increaseCash(amountIn); newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut); } function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool) private returns (uint256 amountCalculated) { bytes32 tokenInBalance; bytes32 tokenOutBalance; // We access both token indexes without checking existence, because we will do it manually immediately after. EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId]; uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn); uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut); if (indexIn == 0 || indexOut == 0) { // The tokens might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(request.poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } // EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid, // we can undo this. indexIn -= 1; indexOut -= 1; uint256 tokenAmount = poolBalances.length(); uint256[] memory currentBalances = new uint256[](tokenAmount); request.lastChangeBlock = 0; for (uint256 i = 0; i < tokenAmount; i++) { // Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we // know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads. bytes32 balance = poolBalances.unchecked_valueAt(i); currentBalances[i] = balance.total(); request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock()); if (i == indexIn) { tokenInBalance = balance; } else if (i == indexOut) { tokenOutBalance = balance; } } // Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut); (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); tokenInBalance = tokenInBalance.increaseCash(amountIn); tokenOutBalance = tokenOutBalance.decreaseCash(amountOut); // Because no tokens were registered or deregistered between now or when we retrieved the indexes for // 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads. poolBalances.unchecked_setAt(indexIn, tokenInBalance); poolBalances.unchecked_setAt(indexOut, tokenOutBalance); } // This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external override returns (int256[] memory) { // In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the // Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it // reverts unconditionally, returning this array as the revert data. // // By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity // function would. The only caveat is the function becomes non-view, but off-chain clients can still call it // via eth_call to get the expected result. // // This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract: // https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265 // // Most of this function is implemented using inline assembly, as the actual work it needs to do is not // significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large // amount of generated bytecode. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the actual asset deltas from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of an array: // length + data. We need to return an ABI-encoded representation of this array. // An ABI-encoded array contains an additional field when compared to its raw memory // representation: an offset to the location of the length. The offset itself is 32 bytes long, // so the smallest value we can use is 32 for the data to be located immediately after it. mstore(0, 32) // We now copy the raw memory array from returndata into memory. Since the offset takes up 32 // bytes, we start copying at address 0x20. We also get rid of the error signature, which takes // the first four bytes of returndata. let size := sub(returndatasize(), 0x04) returndatacopy(0x20, 0x04, size) // We finally return the ABI-encoded array, which has a total length equal to that of the array // (returndata), plus the 32 bytes for the offset. return(0, add(size, 32)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of the array in memory, which is composed of a 32 byte length, // followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array // length (stored at `deltas`) by 32. let size := mul(mload(deltas), 32) // We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12. // We store it in the previous slot to the `deltas` array. We know there will be at least one available // slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12) let start := sub(deltas, 0x04) // When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's // length and the error signature. revert(start, add(size, 36)) } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "./BalancerErrors.sol"; import "./ISignaturesValidator.sol"; import "../openzeppelin/EIP712.sol"; /** * @dev Utility for signing Solidity function calls. * * This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables * meta-transaction schemes by appending an EIP712 signature of the original calldata at the end. * * Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs. */ abstract contract SignaturesValidator is ISignaturesValidator, EIP712 { // The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot // for each of these values, even if 'v' is typically an 8 bit value. uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32; // Replay attack prevention for each user. mapping(address => uint256) internal _nextNonce; constructor(string memory name) EIP712(name, "1") { // solhint-disable-previous-line no-empty-blocks } function getDomainSeparator() external view override returns (bytes32) { return _domainSeparatorV4(); } function getNextNonce(address user) external view override returns (uint256) { return _nextNonce[user]; } /** * @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata. */ function _validateSignature(address user, uint256 errorCode) internal { uint256 nextNonce = _nextNonce[user]++; _require(_isSignatureValid(user, nextNonce), errorCode); } function _isSignatureValid(address user, uint256 nonce) private view returns (bool) { uint256 deadline = _deadline(); // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time if (deadline < block.timestamp) { return false; } bytes32 typeHash = _typeHash(); if (typeHash == bytes32(0)) { // Prevent accidental signature validation for functions that don't have an associated type hash. return false; } // All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline). bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline)); bytes32 digest = _hashTypedDataV4(structHash); (uint8 v, bytes32 r, bytes32 s) = _signature(); address recoveredAddress = ecrecover(digest, v, r, s); // ecrecover returns the zero address on recover failure, so we need to handle that explicitly. return recoveredAddress != address(0) && recoveredAddress == user; } /** * @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function * selector (available as `msg.sig`). * * The type hash must conform to the following format: * <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline) * * If 0x00, all signatures will be considered invalid. */ function _typeHash() internal view virtual returns (bytes32); /** * @dev Extracts the signature deadline from extra calldata. * * This function returns bogus data if no signature is included. */ function _deadline() internal pure returns (uint256) { // The deadline is the first extra argument at the end of the original calldata. return uint256(_decodeExtraCalldataWord(0)); } /** * @dev Extracts the signature parameters from extra calldata. * * This function returns bogus data if no signature is included. This is not a security risk, as that data would not * be considered a valid signature in the first place. */ function _signature() internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // v, r and s are appended after the signature deadline, in that order. v = uint8(uint256(_decodeExtraCalldataWord(0x20))); r = _decodeExtraCalldataWord(0x40); s = _decodeExtraCalldataWord(0x60); } /** * @dev Returns the original calldata, without the extra bytes containing the signature. * * This function returns bogus data if no signature is included. */ function _calldata() internal pure returns (bytes memory result) { result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents. if (result.length > _EXTRA_CALLDATA_LENGTH) { // solhint-disable-next-line no-inline-assembly assembly { // We simply overwrite the array length with the reduced one. mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH)) } } } /** * @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata. * * This function returns bogus data if no signature is included. */ function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) { // solhint-disable-next-line no-inline-assembly assembly { result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; // Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size. /** * @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() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // 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: GPL-3.0-or-later // 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 experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @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). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address 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. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./ProtocolFeesCollector.sol"; import "./VaultAuthorization.sol"; import "./interfaces/IVault.sol"; /** * @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the * ProtocolFeesCollector contract. */ abstract contract Fees is IVault { using SafeERC20 for IERC20; ProtocolFeesCollector private immutable _protocolFeesCollector; constructor() { _protocolFeesCollector = new ProtocolFeesCollector(IVault(this)); } function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) { return _protocolFeesCollector; } /** * @dev Returns the protocol swap fee percentage. */ function _getProtocolSwapFeePercentage() internal view returns (uint256) { return getProtocolFeesCollector().getSwapFeePercentage(); } /** * @dev Returns the protocol fee amount to charge for a flash loan of `amount`. */ function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) { // Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged // percentage can be slightly higher than intended. uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage(); return FixedPoint.mulUp(amount, percentage); } function _payFeeAmount(IERC20 token, uint256 amount) internal { if (amount > 0) { token.safeTransfer(address(getProtocolFeesCollector()), amount); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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 internal License for more details. // You should have received a copy of the GNU General internal License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ห†7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eห†(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ห†6 int256 constant a1 = 6235149080811616882910000000; // eห†(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ห†5 int256 constant a2 = 7896296018268069516100000000000000; // eห†(x2) int256 constant x3 = 1600000000000000000000; // 2ห†4 int256 constant a3 = 888611052050787263676000000; // eห†(x3) int256 constant x4 = 800000000000000000000; // 2ห†3 int256 constant a4 = 298095798704172827474000; // eห†(x4) int256 constant x5 = 400000000000000000000; // 2ห†2 int256 constant a5 = 5459815003314423907810; // eห†(x5) int256 constant x6 = 200000000000000000000; // 2ห†1 int256 constant a6 = 738905609893065022723; // eห†(x6) int256 constant x7 = 100000000000000000000; // 2ห†0 int256 constant a7 = 271828182845904523536; // eห†(x7) int256 constant x8 = 50000000000000000000; // 2ห†-1 int256 constant a8 = 164872127070012814685; // eห†(x8) int256 constant x9 = 25000000000000000000; // 2ห†-2 int256 constant a9 = 128402541668774148407; // eห†(x9) int256 constant x10 = 12500000000000000000; // 2ห†-3 int256 constant a10 = 113314845306682631683; // eห†(x10) int256 constant x11 = 6250000000000000000; // 2ห†-4 int256 constant a11 = 106449445891785942956; // eห†(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = ln_36(base); } else { logBase = ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = ln_36(arg); } else { logArg = ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following: // * a map from IERC20 to bytes32 // * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks // * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios // * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios // // Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation // for IERC20 keys, to reduce bytecode size and runtime costs. // We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule // solhint-disable func-name-mixedcase import "./IERC20.sol"; import "../helpers/BalancerErrors.sol"; /** * @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; * } * ``` */ library EnumerableMap { // The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with // IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode. struct IERC20ToBytes32MapEntry { IERC20 _key; bytes32 _value; } struct IERC20ToBytes32Map { // Number of entries in the map uint256 _length; // Storage of map keys and values mapping(uint256 => IERC20ToBytes32MapEntry) _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(IERC20 => 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( IERC20ToBytes32Map storage map, IERC20 key, bytes32 value ) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) if (keyIndex == 0) { uint256 previousLength = map._length; map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value }); map._length = previousLength + 1; // The entry is stored at previousLength, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = previousLength + 1; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Updates the value for an entry, given its key's index. The key index can be retrieved via * {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1). * * This function performs one less storage read than {set}, but it should only be used when `index` is known to be * within bounds. */ function unchecked_setAt( IERC20ToBytes32Map storage map, uint256 index, bytes32 value ) internal { map._entries[index]._value = value; } /** * @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(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) if (keyIndex != 0) { // To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the // one at the highest index, and then remove this last entry (sometimes called as 'swap and pop'). // This modifies the order of the pseudo-array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._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. IERC20ToBytes32MapEntry 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 delete map._entries[lastIndex]; map._length = lastIndex; // 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(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(IERC20ToBytes32Map storage map) internal view returns (uint256) { return map._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(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { _require(map._length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(map, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { IERC20ToBytes32MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage * read). O(1). */ function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) { return map._entries[index]._value; } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. Reverts with `errorCode` otherwise. */ function get( IERC20ToBytes32Map storage map, IERC20 key, uint256 errorCode ) internal view returns (bytes32) { uint256 index = map._indexes[key]; _require(index > 0, errorCode); return unchecked_valueAt(map, index - 1); } /** * @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0 * instead. */ function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) { return map._indexes[key]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; // Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that // work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime // costs. // The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios. /** * @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 { // The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with // AddressSet, which uses address keys natively, resulting in more dense bytecode. struct AddressSet { // Storage of set values address[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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. address 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(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) { _require(set._values.length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(set, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) { return set._values[index]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { _require(value < 2**255, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256); return int256(value); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./Fees.sol"; import "./PoolTokens.sol"; import "./UserBalance.sol"; import "./interfaces/IBasePool.sol"; /** * @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces, * such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool` * and `getPoolTokens`, delegating to specialization-specific functions as needed. * * `managePoolBalance` handles all Asset Manager interactions. */ abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance { using Math for uint256; using SafeERC20 for IERC20; using BalanceAllocation for bytes32; using BalanceAllocation for bytes32[]; function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable override whenNotPaused { // This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead. // Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both // joins and exits at once. _joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request)); } function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external override { // This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead. _joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request)); } // This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and // `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite // similar, but expose the others to callers for clarity. struct PoolBalanceChange { IAsset[] assets; uint256[] limits; bytes userData; bool useInternalBalance; } /** * @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost. */ function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { // solhint-disable-next-line no-inline-assembly assembly { change := request } } /** * @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost. */ function _toPoolBalanceChange(ExitPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { // solhint-disable-next-line no-inline-assembly assembly { change := request } } /** * @dev Implements both `joinPool` and `exitPool`, based on `kind`. */ function _joinOrExit( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change ) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) { // This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees, // etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary // interfaces to work around this limitation. InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length); // We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the // current balance for each. IERC20[] memory tokens = _translateToIERC20(change.assets); bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens); // The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed, // assets are transferred, and fees are paid. ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory paidProtocolSwapFeeAmounts ) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances); // All that remains is storing the new Pool balances. PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances); } else { // PoolSpecialization.GENERAL _setGeneralPoolBalances(poolId, finalBalances); } bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative emit PoolBalanceChanged( poolId, sender, tokens, // We can unsafely cast to int256 because balances are actually stored as uint112 _unsafeCastToInt256(amountsInOrOut, positive), paidProtocolSwapFeeAmounts ); } /** * @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the * associated token transfers and fee payments, returning the Pool's final balances. */ function _callPoolBalanceChange( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances ) private returns ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory dueProtocolFeeAmounts ) { (uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock(); IBasePool pool = IBasePool(_getPoolAddress(poolId)); (amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN ? pool.onJoinPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ) : pool.onExitPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ); InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length); // The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of // their participation. finalBalances = kind == PoolBalanceChangeKind.JOIN ? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts) : _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts); } /** * @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays * accumulated protocol swap fees. * * Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol * swap fees. */ function _processJoinPoolTransfers( address sender, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { // We need to track how much of the received ETH was used and wrapped into WETH to return any excess. uint256 wrappedEth = 0; finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountIn = amountsIn[i]; _require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX); // Receive assets from the sender - possibly from Internal Balance. IAsset asset = change.assets[i]; _receiveAsset(asset, amountIn, sender, change.useInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(amountIn); } uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); // Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`, // resulting in an overall decrease of the Pool's balance for a token. finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic ? balances[i].increaseCash(amountIn - feeAmount) : balances[i].decreaseCash(feeAmount - amountIn); } // Handle any used and remaining ETH. _handleRemainingEth(wrappedEth); } /** * @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays * accumulated protocol swap fees from the Pool. * * Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid * (`dueProtocolFeeAmounts`). */ function _processExitPoolTransfers( address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountOut = amountsOut[i]; _require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN); // Send tokens to the recipient - possibly to Internal Balance IAsset asset = change.assets[i]; _sendAsset(asset, amountOut, recipient, change.useInternalBalance); uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); // Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0). finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount)); } } /** * @dev Returns the total balance for `poolId`'s `expectedTokens`. * * `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same * length, elements and order. Additionally, the Pool must have at least one registered token. */ function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens) private view returns (bytes32[] memory) { (IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId); InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length); _require(actualTokens.length > 0, Errors.POOL_NO_TOKENS); for (uint256 i = 0; i < actualTokens.length; ++i) { _require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH); } return balances; } /** * @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag, * without checking whether the values fit in the signed 256 bit range. */ function _unsafeCastToInt256(uint256[] memory values, bool positive) private pure returns (int256[] memory signedValues) { signedValues = new int256[](values.length); for (uint256 i = 0; i < values.length; i++) { signedValues[i] = positive ? int256(values[i]) : -int256(values[i]); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "../../lib/math/Math.sol"; // This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many // tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the // Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including // tokens that are *not* inside of the Vault. // // 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are // moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash' // and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events // transferring funds to and from the Asset Manager. // // The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are // not inside the Vault. // // One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use // 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and // 'managed' that yields a 'total' that doesn't fit in 112 bits. // // The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This // can be used to implement price oracles that are resilient to 'sandwich' attacks. // // We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately // Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes // up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot // (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual // packing and unpacking. // // Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any // associated arithmetic operations and therefore reduces the chance of misuse. library BalanceAllocation { using Math for uint256; // The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the // 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block /** * @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed'). */ function total(bytes32 balance) internal pure returns (uint256) { // Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance` // ensures that 'total' always fits in 112 bits. return cash(balance) + managed(balance); } /** * @dev Returns the amount of Pool tokens currently in the Vault. */ function cash(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(balance) & mask; } /** * @dev Returns the amount of Pool tokens that are being managed by an Asset Manager. */ function managed(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(balance >> 112) & mask; } /** * @dev Returns the last block when the total balance changed. */ function lastChangeBlock(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(32) - 1; return uint256(balance >> 224) & mask; } /** * @dev Returns the difference in 'managed' between two balances. */ function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) { // Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits. return int256(managed(newBalance)) - int256(managed(oldBalance)); } /** * @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total * balance of *any* of them last changed. */ function totalsAndLastChangeBlock(bytes32[] memory balances) internal pure returns ( uint256[] memory results, uint256 lastChangeBlock_ // Avoid shadowing ) { results = new uint256[](balances.length); lastChangeBlock_ = 0; for (uint256 i = 0; i < results.length; i++) { bytes32 balance = balances[i]; results[i] = total(balance); lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance)); } } /** * @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing * with zero. */ function isZero(bytes32 balance) internal pure returns (bool) { // We simply need to check the least significant 224 bytes of the word: the block does not affect this. uint256 mask = 2**(224) - 1; return (uint256(balance) & mask) == 0; } /** * @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing * with zero. */ function isNotZero(bytes32 balance) internal pure returns (bool) { return !isZero(balance); } /** * @dev Packs together `cash` and `managed` amounts with a block to create a balance value. * * For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits. */ function toBalance( uint256 _cash, uint256 _managed, uint256 _blockNumber ) internal pure returns (bytes32) { uint256 _total = _cash + _managed; // Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits // we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits. _require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW); // We assume the block fits in 32 bits - this is expected to hold for at least a few decades. return _pack(_cash, _managed, _blockNumber); } /** * @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except * for Asset Manager deposits). * * Updates the last total balance change block, even if `amount` is zero. */ function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) { uint256 newCash = cash(balance).add(amount); uint256 currentManaged = managed(balance); uint256 newLastChangeBlock = block.number; return toBalance(newCash, currentManaged, newLastChangeBlock); } /** * @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault * (except for Asset Manager withdrawals). * * Updates the last total balance change block, even if `amount` is zero. */ function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) { uint256 newCash = cash(balance).sub(amount); uint256 currentManaged = managed(balance); uint256 newLastChangeBlock = block.number; return toBalance(newCash, currentManaged, newLastChangeBlock); } /** * @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens * from the Vault. */ function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) { uint256 newCash = cash(balance).sub(amount); uint256 newManaged = managed(balance).add(amount); uint256 currentLastChangeBlock = lastChangeBlock(balance); return toBalance(newCash, newManaged, currentLastChangeBlock); } /** * @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens * into the Vault. */ function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) { uint256 newCash = cash(balance).add(amount); uint256 newManaged = managed(balance).sub(amount); uint256 currentLastChangeBlock = lastChangeBlock(balance); return toBalance(newCash, newManaged, currentLastChangeBlock); } /** * @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports * profits or losses. It's the Manager's responsibility to provide a meaningful value. * * Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value. */ function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) { uint256 currentCash = cash(balance); uint256 newLastChangeBlock = block.number; return toBalance(currentCash, newManaged, newLastChangeBlock); } // Alternative mode for Pools with the Two Token specialization setting // Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash // for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps, // because the only slot that needs to be updated is the one with the cash. However, it also means that managing // balances is more cumbersome, as both tokens need to be read/written at the same time. // // The field with both cash balances packed is called sharedCash, and the one with external amounts is called // sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion // that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part // uses the next least significant 112 bits. // // Because only cash is written to during a swap, we store the last total balance change block with the // packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they // are the same. /** * @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both * shared cash and managed balances. */ function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance) & mask; } /** * @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both * shared cash and managed balances. */ function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance >> 112) & mask; } // To decode the last balance change block, we can simply use the `blockNumber` function. /** * @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A. */ function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) { // Note that we extract the block from the sharedCash field, which is the one that is updated by swaps. // Both token A and token B use the same block return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash)); } /** * @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B. */ function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) { // Note that we extract the block from the sharedCash field, which is the one that is updated by swaps. // Both token A and token B use the same block return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash)); } /** * @dev Returns the sharedCash shared field, given the current balances for token A and token B. */ function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) { // Both balances are assigned the same block Since it is possible a single one of them has changed (for // example, in an Asset Manager update), we keep the latest (largest) one. uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance))); return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock); } /** * @dev Returns the sharedManaged shared field, given the current balances for token A and token B. */ function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) { // We don't bother storing a last change block, as it is read from the shared cash field. return _pack(managed(tokenABalance), managed(tokenBBalance), 0); } // Shared functions /** * @dev Packs together two uint112 and one uint32 into a bytes32 */ function _pack( uint256 _leastSignificant, uint256 _midSignificant, uint256 _mostSignificant ) private pure returns (bytes32) { return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./AssetManagers.sol"; import "./PoolRegistry.sol"; import "./balances/BalanceAllocation.sol"; abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers { using BalanceAllocation for bytes32; using BalanceAllocation for bytes32[]; function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external override nonReentrant whenNotPaused onlyPool(poolId) { InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length); // Validates token addresses and assigns Asset Managers for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; _require(token != IERC20(0), Errors.INVALID_TOKEN); _poolAssetManagers[poolId][token] = assetManagers[i]; } PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2); _registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _registerMinimalSwapInfoPoolTokens(poolId, tokens); } else { // PoolSpecialization.GENERAL _registerGeneralPoolTokens(poolId, tokens); } emit TokensRegistered(poolId, tokens, assetManagers); } function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external override nonReentrant whenNotPaused onlyPool(poolId) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2); _deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _deregisterMinimalSwapInfoPoolTokens(poolId, tokens); } else { // PoolSpecialization.GENERAL _deregisterGeneralPoolTokens(poolId, tokens); } // The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any // associated Asset Managers, since they hold no Pool balance. for (uint256 i = 0; i < tokens.length; ++i) { delete _poolAssetManagers[poolId][tokens[i]]; } emit TokensDeregistered(poolId, tokens); } function getPoolTokens(bytes32 poolId) external view override withRegisteredPool(poolId) returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ) { bytes32[] memory rawBalances; (tokens, rawBalances) = _getPoolTokens(poolId); (balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock(); } function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view override withRegisteredPool(poolId) returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ) { bytes32 balance; PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { balance = _getTwoTokenPoolBalance(poolId, token); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { balance = _getMinimalSwapInfoPoolBalance(poolId, token); } else { // PoolSpecialization.GENERAL balance = _getGeneralPoolBalance(poolId, token); } cash = balance.cash(); managed = balance.managed(); lastChangeBlock = balance.lastChangeBlock(); assetManager = _poolAssetManagers[poolId][token]; } /** * @dev Returns all of `poolId`'s registered tokens, along with their raw balances. */ function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { return _getTwoTokenPoolTokens(poolId); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { return _getMinimalSwapInfoPoolTokens(poolId); } else { // PoolSpecialization.GENERAL return _getGeneralPoolTokens(poolId); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeCast.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./AssetTransfersHandler.sol"; import "./VaultAuthorization.sol"; /** * Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance. * * Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later * transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination * when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced * gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. * * Internal Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different senders and recipients, at once. */ abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization { using Math for uint256; using SafeCast for uint256; using SafeERC20 for IERC20; // Internal Balance for each token, for each account. mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance; function getInternalBalance(address user, IERC20[] memory tokens) external view override returns (uint256[] memory balances) { balances = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { balances[i] = _getInternalBalance(user, tokens[i]); } } function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant { // We need to track how much of the received ETH was used and wrapped into WETH to return any excess. uint256 ethWrapped = 0; // Cache for these checks so we only perform them once (if at all). bool checkedCallerIsRelayer = false; bool checkedNotPaused = false; for (uint256 i = 0; i < ops.length; i++) { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; // This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size. (kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp( ops[i], checkedCallerIsRelayer ); if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) { // Internal Balance withdrawals can always be performed by an authorized account. _withdrawFromInternalBalance(asset, sender, recipient, amount); } else { // All other operations are blocked if the contract is paused. // We cache the result of the pause check and skip it for other operations in this same transaction // (if any). if (!checkedNotPaused) { _ensureNotPaused(); checkedNotPaused = true; } if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) { _depositToInternalBalance(asset, sender, recipient, amount); // Keep track of all ETH wrapped into WETH as part of a deposit. if (_isETH(asset)) { ethWrapped = ethWrapped.add(amount); } } else { // Transfers don't support ETH. _require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL); IERC20 token = _asIERC20(asset); if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) { _transferInternalBalance(token, sender, recipient, amount); } else { // TRANSFER_EXTERNAL _transferToExternalBalance(token, sender, recipient, amount); } } } } // Handle any remaining ETH. _handleRemainingEth(ethWrapped); } function _depositToInternalBalance( IAsset asset, address sender, address recipient, uint256 amount ) private { _increaseInternalBalance(recipient, _translateToIERC20(asset), amount); _receiveAsset(asset, amount, sender, false); } function _withdrawFromInternalBalance( IAsset asset, address sender, address payable recipient, uint256 amount ) private { // A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`. _decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false); _sendAsset(asset, amount, recipient, false); } function _transferInternalBalance( IERC20 token, address sender, address recipient, uint256 amount ) private { // A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`. _decreaseInternalBalance(sender, token, amount, false); _increaseInternalBalance(recipient, token, amount); } function _transferToExternalBalance( IERC20 token, address sender, address recipient, uint256 amount ) private { if (amount > 0) { token.safeTransferFrom(sender, recipient, amount); emit ExternalBalanceTransfer(token, sender, recipient, amount); } } /** * @dev Increases `account`'s Internal Balance for `token` by `amount`. */ function _increaseInternalBalance( address account, IERC20 token, uint256 amount ) internal override { uint256 currentBalance = _getInternalBalance(account, token); uint256 newBalance = currentBalance.add(amount); _setInternalBalance(account, token, newBalance, amount.toInt256()); } /** * @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function * doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount * instead. */ function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool allowPartial ) internal override returns (uint256 deducted) { uint256 currentBalance = _getInternalBalance(account, token); _require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE); deducted = Math.min(currentBalance, amount); // By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked // arithmetic. uint256 newBalance = currentBalance - deducted; _setInternalBalance(account, token, newBalance, -(deducted.toInt256())); } /** * @dev Sets `account`'s Internal Balance for `token` to `newBalance`. * * Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased * (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta, * this function relies on the caller providing it directly. */ function _setInternalBalance( address account, IERC20 token, uint256 newBalance, int256 delta ) private { _internalTokenBalance[account][token] = newBalance; emit InternalBalanceChanged(account, token, delta); } /** * @dev Returns `account`'s Internal Balance for `token`. */ function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) { return _internalTokenBalance[account][token]; } /** * @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it. */ function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer) private view returns ( UserBalanceOpKind, IAsset, uint256, address, address payable, bool ) { // The only argument we need to validate is `sender`, which can only be either the contract caller, or a // relayer approved by `sender`. address sender = op.sender; if (sender != msg.sender) { // We need to check both that the contract caller is a relayer, and that `sender` approved them. // Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for // other operations in this same transaction (if any). if (!checkedCallerIsRelayer) { _authenticateCaller(); checkedCallerIsRelayer = true; } _require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER); } return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./UserBalance.sol"; import "./balances/BalanceAllocation.sol"; import "./balances/GeneralPoolsBalance.sol"; import "./balances/MinimalSwapInfoPoolsBalance.sol"; import "./balances/TwoTokenPoolsBalance.sol"; abstract contract AssetManagers is ReentrancyGuard, GeneralPoolsBalance, MinimalSwapInfoPoolsBalance, TwoTokenPoolsBalance { using Math for uint256; using SafeERC20 for IERC20; // Stores the Asset Manager for each token of each Pool. mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers; function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused { // This variable could be declared inside the loop, but that causes the compiler to allocate memory on each // loop iteration, increasing gas costs. PoolBalanceOp memory op; for (uint256 i = 0; i < ops.length; ++i) { // By indexing the array only once, we don't spend extra gas in the same bounds check. op = ops[i]; bytes32 poolId = op.poolId; _ensureRegisteredPool(poolId); IERC20 token = op.token; _require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED); _require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER); PoolBalanceOpKind kind = op.kind; uint256 amount = op.amount; (int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount); emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta); } } /** * @dev Performs the `kind` Asset Manager operation on a Pool. * * Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller, * and updates will set the managed balance to `amount`. * * Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call. */ function _performPoolManagementOperation( PoolBalanceOpKind kind, bytes32 poolId, IERC20 token, uint256 amount ) private returns (int256, int256) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (kind == PoolBalanceOpKind.WITHDRAW) { return _withdrawPoolBalance(poolId, specialization, token, amount); } else if (kind == PoolBalanceOpKind.DEPOSIT) { return _depositPoolBalance(poolId, specialization, token, amount); } else { // PoolBalanceOpKind.UPDATE return _updateManagedBalance(poolId, specialization, token, amount); } } /** * @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller. * * Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary. */ function _withdrawPoolBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { _twoTokenPoolCashToManaged(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _minimalSwapInfoPoolCashToManaged(poolId, token, amount); } else { // PoolSpecialization.GENERAL _generalPoolCashToManaged(poolId, token, amount); } if (amount > 0) { token.safeTransfer(msg.sender, amount); } // Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will // therefore always fit in a 256 bit integer. cashDelta = int256(-amount); managedDelta = int256(amount); } /** * @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller. * * Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary. */ function _depositPoolBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { _twoTokenPoolManagedToCash(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _minimalSwapInfoPoolManagedToCash(poolId, token, amount); } else { // PoolSpecialization.GENERAL _generalPoolManagedToCash(poolId, token, amount); } if (amount > 0) { token.safeTransferFrom(msg.sender, address(this), amount); } // Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will // therefore always fit in a 256 bit integer. cashDelta = int256(amount); managedDelta = int256(-amount); } /** * @dev Sets a Pool's 'managed' balance to `amount`. * * Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero). */ function _updateManagedBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount); } else { // PoolSpecialization.GENERAL managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount); } cashDelta = 0; } /** * @dev Returns true if `token` is registered for `poolId`. */ function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { return _isTwoTokenPoolTokenRegistered(poolId, token); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { return _isMinimalSwapInfoPoolTokenRegistered(poolId, token); } else { // PoolSpecialization.GENERAL return _isGeneralPoolTokenRegistered(poolId, token); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./VaultAuthorization.sol"; /** * @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers * and helper functions for ensuring correct behavior when working with Pools. */ abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization { // Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new // types. mapping(bytes32 => bool) private _isPoolRegistered; // We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a // `uint256` results in reduced bytecode on reads and writes due to the lack of masking. uint256 private _nextPoolNonce; /** * @dev Reverts unless `poolId` corresponds to a registered Pool. */ modifier withRegisteredPool(bytes32 poolId) { _ensureRegisteredPool(poolId); _; } /** * @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract. */ modifier onlyPool(bytes32 poolId) { _ensurePoolIsSender(poolId); _; } /** * @dev Reverts unless `poolId` corresponds to a registered Pool. */ function _ensureRegisteredPool(bytes32 poolId) internal view { _require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); } /** * @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract. */ function _ensurePoolIsSender(bytes32 poolId) private view { _ensureRegisteredPool(poolId); _require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL); } function registerPool(PoolSpecialization specialization) external override nonReentrant whenNotPaused returns (bytes32) { // Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than // 2**80 Pools, and the nonce will not overflow. bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce)); _require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique. _isPoolRegistered[poolId] = true; _nextPoolNonce += 1; // Note that msg.sender is the pool's contract emit PoolRegistered(poolId, msg.sender, specialization); return poolId; } function getPool(bytes32 poolId) external view override withRegisteredPool(poolId) returns (address, PoolSpecialization) { return (_getPoolAddress(poolId), _getPoolSpecialization(poolId)); } /** * @dev Creates a Pool ID. * * These are deterministically created by packing the Pool's contract address and its specialization setting into * the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses. * * Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are * unique. * * Pool IDs have the following layout: * | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce | * MSB LSB * * 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would * suffice. However, there's nothing else of interest to store in this extra space. */ function _toPoolId( address pool, PoolSpecialization specialization, uint80 nonce ) internal pure returns (bytes32) { bytes32 serialized; serialized |= bytes32(uint256(nonce)); serialized |= bytes32(uint256(specialization)) << (10 * 8); serialized |= bytes32(uint256(pool)) << (12 * 8); return serialized; } /** * @dev Returns the address of a Pool's contract. * * Due to how Pool IDs are created, this is done with no storage accesses and costs little gas. */ function _getPoolAddress(bytes32 poolId) internal pure returns (address) { // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask, // since the logical shift already sets the upper bits to zero. return address(uint256(poolId) >> (12 * 8)); } /** * @dev Returns the specialization setting of a Pool. * * Due to how Pool IDs are created, this is done with no storage accesses and costs little gas. */ function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) { // 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address. uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1); // Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's // range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason // string: we instead perform the check ourselves to help in error diagnosis. // There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to // values 0, 1 and 2. _require(value < 3, Errors.INVALID_POOL_ID); // Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check. // solhint-disable-next-line no-inline-assembly assembly { specialization := value } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/EnumerableMap.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; abstract contract GeneralPoolsBalance { using BalanceAllocation for bytes32; using EnumerableMap for EnumerableMap.IERC20ToBytes32Map; // Data for Pools with the General specialization setting // // These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their // tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas // intensive to read all token addresses just to then do a lookup on the balance mapping. // // Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for // each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call), // and update an entry's value given its index. // Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to // a Pool's EnumerableMap to save gas when computing storage slots. mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances; /** * @dev Registers a list of tokens in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `tokens` must not be registered in the Pool * - `tokens` must not contain duplicates */ function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { // EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same // value that is found in uninitialized storage, which corresponds to an empty balance. bool added = poolBalances.set(tokens[i], 0); _require(added, Errors.TOKEN_ALREADY_REGISTERED); } } /** * @dev Deregisters a list of tokens in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `tokens` must be registered in the Pool * - `tokens` must have zero balance in the Vault * - `tokens` must not contain duplicates */ function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token); _require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE); // We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token // was registered. poolBalances.remove(token); } } /** * @dev Sets the balances of a General Pool's tokens to `balances`. * * WARNING: this assumes `balances` has the same length and order as the Pool's tokens. */ function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < balances.length; ++i) { // Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less // storage read per token. poolBalances.unchecked_setAt(i, balances[i]); } } /** * @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. */ function _generalPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. */ function _generalPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a General Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setGeneralPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the * current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateGeneralPoolBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) private returns (int256) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token); bytes32 newBalance = mutation(currentBalance, amount); poolBalances.set(token, newBalance); return newBalance.managedDelta(currentBalance); } /** * @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are * registered or deregistered. * * This function assumes `poolId` exists and corresponds to the General specialization setting. */ function _getGeneralPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; tokens = new IERC20[](poolBalances.length()); balances = new bytes32[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { // Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use // `unchecked_at` as we know `i` is a valid token index, saving storage reads. (tokens[i], balances[i]) = poolBalances.unchecked_at(i); } } /** * @dev Returns the balance of a token in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `token` must be registered in the Pool */ function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return _getGeneralPoolBalance(poolBalances, token); } /** * @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and * writes. */ function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token) private view returns (bytes32) { return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED); } /** * @dev Returns true if `token` is registered in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. */ function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return poolBalances.contains(token); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/EnumerableSet.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; import "../PoolRegistry.sol"; abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry { using BalanceAllocation for bytes32; using EnumerableSet for EnumerableSet.AddressSet; // Data for Pools with the Minimal Swap Info specialization setting // // These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens // in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's // balance in a single storage access. // // We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in // some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by // performing a single read instead of two. mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances; mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens; /** * @dev Registers a list of tokens in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. * * Requirements: * * - `tokens` must not be registered in the Pool * - `tokens` must not contain duplicates */ function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { bool added = poolTokens.add(address(tokens[i])); _require(added, Errors.TOKEN_ALREADY_REGISTERED); // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } } /** * @dev Deregisters a list of tokens in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. * * Requirements: * * - `tokens` must be registered in the Pool * - `tokens` must have zero balance in the Vault * - `tokens` must not contain duplicates */ function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; _require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE); // For consistency with other Pool specialization settings, we explicitly reset the balance (which may have // a non-zero last change block). delete _minimalSwapInfoPoolsBalances[poolId][token]; bool removed = poolTokens.remove(address(token)); _require(removed, Errors.TOKEN_NOT_REGISTERED); } } /** * @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`. * * WARNING: this assumes `balances` has the same length and order as the Pool's tokens. */ function _setMinimalSwapInfoPoolBalances( bytes32 poolId, IERC20[] memory tokens, bytes32[] memory balances ) internal { for (uint256 i = 0; i < tokens.length; ++i) { _minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i]; } } /** * @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. */ function _minimalSwapInfoPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. */ function _minimalSwapInfoPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setMinimalSwapInfoPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with * the current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateMinimalSwapInfoPoolBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) internal returns (int256) { bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token); bytes32 newBalance = mutation(currentBalance, amount); _minimalSwapInfoPoolsBalances[poolId][token] = newBalance; return newBalance.managedDelta(currentBalance); } /** * @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when * tokens are registered or deregistered. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. */ function _getMinimalSwapInfoPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; tokens = new IERC20[](poolTokens.length()); balances = new bytes32[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { // Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use // `unchecked_at` as we know `i` is a valid token index, saving storage reads. IERC20 token = IERC20(poolTokens.unchecked_at(i)); tokens[i] = token; balances[i] = _minimalSwapInfoPoolsBalances[poolId][token]; } } /** * @dev Returns the balance of a token in a Minimal Swap Info Pool. * * Requirements: * * - `poolId` must be a Minimal Swap Info Pool * - `token` must be registered in the Pool */ function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token]; // A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is // registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save // gas by not performing the check. bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token)); if (!tokenRegistered) { // The token might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } return balance; } /** * @dev Returns true if `token` is registered in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. */ function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; return poolTokens.contains(address(token)); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; import "../PoolRegistry.sol"; abstract contract TwoTokenPoolsBalance is PoolRegistry { using BalanceAllocation for bytes32; // Data for Pools with the Two Token specialization setting // // These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there // are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little // sense, as it will only ever hold two tokens, so we can just store those two directly. // // The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token // A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need // to write to this second storage slot. A single last change block number for both tokens is stored with the packed // cash fields. struct TwoTokenPoolBalances { bytes32 sharedCash; bytes32 sharedManaged; } // We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to // which tokens those balances correspond. This would mean having to also check which are registered with the Pool. // // What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances // struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to // that pair's hash). // // This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be // accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash // is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A, // and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead. // // If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry // that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair // are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save // storage reads. struct TwoTokenPoolTokens { IERC20 tokenA; IERC20 tokenB; mapping(bytes32 => TwoTokenPoolBalances) balances; } mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens; /** * @dev Registers tokens in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. * * Requirements: * * - `tokenX` and `tokenY` must not be the same * - The tokens must be ordered: tokenX < tokenY */ function _registerTwoTokenPoolTokens( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal { // Not technically true since we didn't register yet, but this is consistent with the error messages of other // specialization settings. _require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED); _require(tokenX < tokenY, Errors.UNSORTED_TOKENS); // A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B. TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; _require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET); // Since tokenX < tokenY, tokenX is A and tokenY is B poolTokens.tokenA = tokenX; poolTokens.tokenB = tokenY; // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } /** * @dev Deregisters tokens in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. * * Requirements: * * - `tokenX` and `tokenY` must be registered in the Pool * - both tokens must have zero balance in the Vault */ function _deregisterTwoTokenPoolTokens( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal { ( bytes32 balanceA, bytes32 balanceB, TwoTokenPoolBalances storage poolBalances ) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY); _require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE); delete _twoTokenPoolTokens[poolId]; // For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may // have a non-zero last change block). delete poolBalances.sharedCash; } /** * @dev Sets the cash balances of a Two Token Pool's tokens. * * WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order. */ function _setTwoTokenPoolCashBalances( bytes32 poolId, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB ) internal { bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash]; poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB); } /** * @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. */ function _twoTokenPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. */ function _twoTokenPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a Two Token Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setTwoTokenPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with * the current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateTwoTokenPoolSharedBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) private returns (int256) { ( TwoTokenPoolBalances storage balances, IERC20 tokenA, bytes32 balanceA, , bytes32 balanceB ) = _getTwoTokenPoolBalances(poolId); int256 delta; if (token == tokenA) { bytes32 newBalance = mutation(balanceA, amount); delta = newBalance.managedDelta(balanceA); balanceA = newBalance; } else { // token == tokenB bytes32 newBalance = mutation(balanceB, amount); delta = newBalance.managedDelta(balanceB); balanceB = newBalance; } balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB); balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB); return delta; } /* * @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when * tokens are registered or deregistered. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. */ function _getTwoTokenPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); // Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for // clarity. if (tokenA == IERC20(0) || tokenB == IERC20(0)) { return (new IERC20[](0), new bytes32[](0)); } // Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B) // ordering. tokens = new IERC20[](2); tokens[0] = tokenA; tokens[1] = tokenB; balances = new bytes32[](2); balances[0] = balanceA; balances[1] = balanceB; } /** * @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using * an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it * without having to recompute the pair hash and storage slot. */ function _getTwoTokenPoolBalances(bytes32 poolId) private view returns ( TwoTokenPoolBalances storage poolBalances, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB ) { TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; tokenA = poolTokens.tokenA; tokenB = poolTokens.tokenB; bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); poolBalances = poolTokens.balances[pairHash]; bytes32 sharedCash = poolBalances.sharedCash; bytes32 sharedManaged = poolBalances.sharedManaged; balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged); balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged); } /** * @dev Returns the balance of a token in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive * operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface. * * Requirements: * * - `token` must be registered in the Pool */ function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { // We can't just read the balance of token, because we need to know the full pair in order to compute the pair // hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`. (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); if (token == tokenA) { return balanceA; } else if (token == tokenB) { return balanceB; } else { _revert(Errors.TOKEN_NOT_REGISTERED); } } /** * @dev Returns the balance of the two tokens in a Two Token Pool. * * The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and * token B the other. * * This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair, * which can be used to update it without having to recompute the pair hash and storage slot. * * Requirements: * * - `poolId` must be a Minimal Swap Info Pool * - `tokenX` and `tokenY` must be registered in the Pool */ function _getTwoTokenPoolSharedBalances( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal view returns ( bytes32 balanceA, bytes32 balanceB, TwoTokenPoolBalances storage poolBalances ) { (IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY); bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash]; // Because we're reading balances using the pair hash, if either token X or token Y is not registered then // *both* balance entries will be zero. bytes32 sharedCash = poolBalances.sharedCash; bytes32 sharedManaged = poolBalances.sharedManaged; // A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each // token is registered in the Pool. Token registration implies that the Pool is registered as well, which // lets us save gas by not performing the check. bool tokensRegistered = sharedCash.isNotZero() || sharedManaged.isNotZero() || (_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB)); if (!tokensRegistered) { // The tokens might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged); balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged); } /** * @dev Returns true if `token` is registered in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. */ function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; // The zero address can never be a registered token. return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0); } /** * @dev Returns the hash associated with a given token pair. */ function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) { return keccak256(abi.encodePacked(tokenA, tokenB)); } /** * @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple. */ function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) { return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/AssetHelpers.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "../lib/openzeppelin/Address.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IAsset.sol"; import "./interfaces/IVault.sol"; abstract contract AssetTransfersHandler is AssetHelpers { using SafeERC20 for IERC20; using Address for address payable; /** * @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much * as possible from Internal Balance, then transfers any remaining amount. * * If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds * will be wrapped into WETH. * * WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the * caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault * typically doesn't hold any). */ function _receiveAsset( IAsset asset, uint256 amount, address sender, bool fromInternalBalance ) internal { if (amount == 0) { return; } if (_isETH(asset)) { _require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE); // The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for // the Vault at a 1:1 ratio. // A check for this condition is also introduced by the compiler, but this one provides a revert reason. // Note we're checking for the Vault's total balance, *not* ETH sent in this transaction. _require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH); _WETH().deposit{ value: amount }(); } else { IERC20 token = _asIERC20(asset); if (fromInternalBalance) { // We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred. uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true); // Because `deductedBalance` will be always the lesser of the current internal balance // and the amount to decrease, it is safe to perform unchecked arithmetic. amount -= deductedBalance; } if (amount > 0) { token.safeTransferFrom(sender, address(this), amount); } } } /** * @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal * Balance instead of being transferred. * * If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds * are instead sent directly after unwrapping WETH. */ function _sendAsset( IAsset asset, uint256 amount, address payable recipient, bool toInternalBalance ) internal { if (amount == 0) { return; } if (_isETH(asset)) { // Sending ETH is not as involved as receiving it: the only special behavior is it cannot be // deposited to Internal Balance. _require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE); // First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH // from the Vault. This receipt will be handled by the Vault's `receive`. _WETH().withdraw(amount); // Then, the withdrawn ETH is sent to the recipient. recipient.sendValue(amount); } else { IERC20 token = _asIERC20(asset); if (toInternalBalance) { _increaseInternalBalance(recipient, token, amount); } else { token.safeTransfer(recipient, amount); } } } /** * @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts * if the caller sent less ETH than `amountUsed`. * * Because the caller might not know exactly how much ETH a Vault action will require, they may send extra. * Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are * not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this * returned ETH. */ function _handleRemainingEth(uint256 amountUsed) internal { _require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH); uint256 excess = msg.value - amountUsed; if (excess > 0) { msg.sender.sendValue(excess); } } /** * @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the * caller. * * Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so * we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an * ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result * in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to * prevent user error. */ receive() external payable { _require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER); } // This contract uses virtual internal functions instead of inheriting from the modules that implement them (in // this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by // implementing these with mocks. function _increaseInternalBalance( address account, IERC20 token, uint256 amount ) internal virtual; function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool capped ) internal virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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.7.0; import "../openzeppelin/IERC20.sol"; import "../../vault/interfaces/IAsset.sol"; import "../../vault/interfaces/IWETH.sol"; abstract contract AssetHelpers { // solhint-disable-next-line var-name-mixedcase IWETH private immutable _weth; // Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for // multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and // it is an address Pools cannot register as a token. address private constant _ETH = address(0); constructor(IWETH weth) { _weth = weth; } // solhint-disable-next-line func-name-mixedcase function _WETH() internal view returns (IWETH) { return _weth; } /** * @dev Returns true if `asset` is the sentinel value that represents ETH. */ function _isETH(IAsset asset) internal pure returns (bool) { return address(asset) == _ETH; } /** * @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated * to the WETH contract. */ function _translateToIERC20(IAsset asset) internal view returns (IERC20) { return _isETH(asset) ? _WETH() : _asIERC20(asset); } /** * @dev Same as `_translateToIERC20(IAsset)`, but for an entire array. */ function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) { IERC20[] memory tokens = new IERC20[](assets.length); for (uint256 i = 0; i < assets.length; ++i) { tokens[i] = _translateToIERC20(assets[i]); } return tokens; } /** * @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously * returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value. */ function _asIERC20(IAsset asset) internal pure returns (IERC20) { return IERC20(address(asset)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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, Errors.ADDRESS_INSUFFICIENT_BALANCE); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); _require(success, Errors.ADDRESS_CANNOT_SEND_VALUE); } }
Returns the sharedCash shared field, given the current balances for token A and token B./ Both balances are assigned the same block Since it is possible a single one of them has changed (for example, in an Asset Manager update), we keep the latest (largest) one.
function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) { uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance))); return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock); }
642,199
./partial_match/5/0x2a24c0010A0FF581D85eD1ECC6BDb7eb71c525FE/sources/BlockChainedElite.sol
get price and require this payment to be sent split ETH 70% owner 30% stays in BCE add to flips emit purchase of tokenrequire this ID to be valid -- min if correct ETHmint
function purchase(uint256 tokenId) payable public whileSale{ if(_exists(tokenId)){ require(msg.value == getPrice(tokenId), "BCE: Invalid Price"); address prevOwner = ownerOf(tokenId); _transfer(prevOwner, _msgSender(), tokenId); flips[tokenId] = flips[tokenId].add(1); Purchase(tokenId, _msgSender()); require (tokenId <= 100, "BCE: Invalid"); require (tokenId >= 1, "BCE: Invalid"); require (msg.value == 1e17, "BCE: 0.1 ETH"); _safeMint(_msgSender(), tokenId); _setTokenURI(tokenId,presetURI[tokenId]); flips[tokenId] = 1; } }
16,863,102
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/SignatureCheckerLib.sol
@solidity memory-safe-assembly Clean the upper 96 bits of `signer` in case they are dirty. `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
function isValidSignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns (bool isValid) assembly { let m := mload(0x40) mstore(0x00, hash) let t := staticcall( ) if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) { isValid := 1 break } let f := shl(224, 0x1626ba7e) mstore(add(m, 0x04), hash) let d := add(m, 0x24) ) ) break }
4,875,417
./full_match/4/0x9AC3EE2283e7EB9eeD68Ee7f5d313D96d3Eb5039/sources/Contract.sol
function burn( uint256 value) external returns (bool success);
interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); 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); event TokenBuAndSellWithTax(address indexed to , uint256 amount ,uint256 balance); }
705,406
./full_match/137/0x0a49EbdC20DfBcD90A53b4BA4C74a5DBfb42BECa/sources/contracts/libraries/PrimexPricingLibrary.sol
Decodes an encoded path and returns an array of addresses. encodedPath The encoded path to be decoded. dexRouter The address of the DEX router. dexAdapter The address of the DEX adapter. return path An array of addresses representing the decoded path./
function decodePath( bytes memory encodedPath, address dexRouter, address dexAdapter ) public view returns (address[] memory path) { IDexAdapter.DexType type_ = IDexAdapter(dexAdapter).dexType(dexRouter); if (type_ == IDexAdapter.DexType.UniswapV2 || type_ == IDexAdapter.DexType.Meshswap) { path = abi.decode(encodedPath, (address[])); uint256 skip; uint256 pathLength = encodedPath.length / offsetSize + 1; path = new address[](pathLength); for (uint256 i; i < pathLength; i++) { path[i] = encodedPath.toAddress(skip, encodedPath.length); skip += offsetSize; } (path, ) = abi.decode(encodedPath, (address[], address[])); (path, , ) = abi.decode(encodedPath, (address[], bytes32[], int256[])); uint256 skip; uint256 pathLength = encodedPath.length / offsetSize; path = new address[](pathLength); for (uint256 i; i < pathLength; i++) { path[i] = encodedPath.toAddress(skip, encodedPath.length); skip += offsetSize; } _revert(Errors.UNKNOWN_DEX_TYPE.selector); } }
4,795,810
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol'; import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol'; import {IExecutorWithTimelock} from '../interfaces/governance/IExecutorWithTimelock.sol'; import {IVotingPowerStrategy} from '../interfaces/governance/IVotingPowerStrategy.sol'; import {IProposalValidator} from '../interfaces/governance/IProposalValidator.sol'; import {getChainId} from '../misc/Helpers.sol'; /** * @title Kyber Governance contract for Kyber 3.0 * - Create a Proposal * - Cancel a Proposal * - Queue a Proposal * - Execute a Proposal * - Submit Vote to a Proposal * Proposal States : Pending => Active => Succeeded(/Failed/Finalized) * => Queued => Executed(/Expired) * The transition to "Canceled" can appear in multiple states **/ contract KyberGovernance is IKyberGovernance, PermissionAdmin { using SafeMath for uint256; bytes32 public constant DOMAIN_TYPEHASH = keccak256( 'EIP712Domain(string name,uint256 chainId,address verifyingContract)' ); bytes32 public constant VOTE_EMITTED_TYPEHASH = keccak256( 'VoteEmitted(uint256 id,uint256 optionBitMask)' ); string public constant NAME = 'Kyber Governance'; address private _daoOperator; uint256 private _proposalsCount; mapping(uint256 => Proposal) private _proposals; mapping(address => bool) private _authorizedExecutors; mapping(address => bool) private _authorizedVotingPowerStrategies; constructor( address admin, address daoOperator, address[] memory executors, address[] memory votingPowerStrategies ) PermissionAdmin(admin) { require(daoOperator != address(0), 'invalid dao operator'); _daoOperator = daoOperator; _authorizeExecutors(executors); _authorizeVotingPowerStrategies(votingPowerStrategies); } /** * @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param executionParams data for execution, includes * targets list of contracts called by proposal's associated transactions * weiValues list of value in wei for each proposal's associated transaction * signatures list of function signatures (can be empty) to be used when created the callData * calldatas list of calldatas: if associated signature empty, * calldata ready, else calldata is arguments * withDelegatecalls boolean, true = transaction delegatecalls the taget, * else calls the target * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createBinaryProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, BinaryProposalParams memory executionParams, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require(executionParams.targets.length != 0, 'create binary invalid empty targets'); require( executionParams.targets.length == executionParams.weiValues.length && executionParams.targets.length == executionParams.signatures.length && executionParams.targets.length == executionParams.calldatas.length && executionParams.targets.length == executionParams.withDelegatecalls.length, 'create binary inconsistent params length' ); require(isExecutorAuthorized(address(executor)), 'create binary executor not authorized'); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create binary strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateBinaryProposalCreation( strategy, msg.sender, startTime, endTime, _daoOperator ), 'validate proposal creation invalid' ); ProposalWithoutVote storage newProposalData = _proposals[proposalId].proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Binary; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.targets = executionParams.targets; newProposalData.weiValues = executionParams.weiValues; newProposalData.signatures = executionParams.signatures; newProposalData.calldatas = executionParams.calldatas; newProposalData.withDelegatecalls = executionParams.withDelegatecalls; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; // only 2 options, YES and NO newProposalData.options.push('YES'); newProposalData.options.push('NO'); newProposalData.voteCounts.push(0); newProposalData.voteCounts.push(0); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit BinaryProposalCreated( proposalId, msg.sender, executor, strategy, executionParams.targets, executionParams.weiValues, executionParams.signatures, executionParams.calldatas, executionParams.withDelegatecalls, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Creates a Generic Proposal (needs to be validated by the Proposal Validator) * It only gets the winning option without any executions * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param options list of options to vote for * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createGenericProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, string[] memory options, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require( isExecutorAuthorized(address(executor)), 'create generic executor not authorized' ); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create generic strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateGenericProposalCreation( strategy, msg.sender, startTime, endTime, options, _daoOperator ), 'validate proposal creation invalid' ); Proposal storage newProposal = _proposals[proposalId]; ProposalWithoutVote storage newProposalData = newProposal.proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Generic; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; newProposalData.options = options; newProposalData.voteCounts = new uint256[](options.length); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit GenericProposalCreated( proposalId, msg.sender, executor, strategy, options, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Cancels a Proposal. * - Callable by the _daoOperator with relaxed conditions, * or by anybody if the conditions of cancellation on the executor are fulfilled * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalState state = getProposalState(proposalId); require( state != ProposalState.Executed && state != ProposalState.Canceled && state != ProposalState.Expired && state != ProposalState.Finalized, 'invalid state to cancel' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; require( msg.sender == _daoOperator || IProposalValidator(address(proposal.executor)).validateProposalCancellation( IKyberGovernance(this), proposalId, proposal.creator ), 'validate proposal cancellation failed' ); proposal.canceled = true; if (proposal.proposalType == ProposalType.Binary) { for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.cancelTransaction( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } } // notify voting power strategy about the cancellation proposal.strategy.handleProposalCancellation(proposalId); emit ProposalCanceled(proposalId); } /** * @dev Queue the proposal (If Proposal Succeeded), only for Binary proposals * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); require( getProposalState(proposalId) == ProposalState.Succeeded, 'invalid state to queue' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Succeeded state assert(proposal.proposalType == ProposalType.Binary); uint256 executionTime = block.timestamp.add(proposal.executor.getDelay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.executor, proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], executionTime, proposal.withDelegatecalls[i] ); } proposal.executionTime = executionTime; emit ProposalQueued(proposalId, executionTime, msg.sender); } /** * @dev Execute the proposal (If Proposal Queued), only for Binary proposals * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external override payable { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Queued, 'only queued proposals'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Queued state assert(proposal.proposalType == ProposalType.Binary); proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.executeTransaction{value: proposal.weiValues[i]}( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } emit ProposalExecuted(proposalId, msg.sender); } /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param optionBitMask bitmask optionBitMask of voter * for Binary Proposal, optionBitMask should be either 1 or 2 (Accept/Reject) * for Generic Proposal, optionBitMask is the bitmask of voted options **/ function submitVote(uint256 proposalId, uint256 optionBitMask) external override { return _submitVote(msg.sender, proposalId, optionBitMask); } /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param optionBitMask the bit mask of voted options * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, uint256 optionBitMask, uint8 v, bytes32 r, bytes32 s ) external override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), getChainId(), address(this)) ), keccak256(abi.encode(VOTE_EMITTED_TYPEHASH, proposalId, optionBitMask)) ) ); address signer = ecrecover(digest, v, r, s); require(signer != address(0), 'invalid signature'); return _submitVote(signer, proposalId, optionBitMask); } /** * @dev Function to handle voting power changed for a voter * caller must be the voting power strategy of the proposal * @param voter address that has changed the voting power * @param newVotingPower new voting power of that address, * old voting power can be taken from records * @param proposalIds list proposal ids that belongs to this voting power strategy * should update the voteCound of the active proposals in the list **/ function handleVotingPowerChanged( address voter, uint256 newVotingPower, uint256[] calldata proposalIds ) external override { uint224 safeNewVotingPower = _safeUint224(newVotingPower); for (uint256 i = 0; i < proposalIds.length; i++) { // only update for active proposals if (getProposalState(proposalIds[i]) != ProposalState.Active) continue; ProposalWithoutVote storage proposal = _proposals[proposalIds[i]].proposalData; require(address(proposal.strategy) == msg.sender, 'invalid voting power strategy'); Vote memory vote = _proposals[proposalIds[i]].votes[voter]; if (vote.optionBitMask == 0) continue; // not voted yet uint256 oldVotingPower = uint256(vote.votingPower); // update totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(newVotingPower).sub(oldVotingPower); for (uint256 j = 0; j < proposal.options.length; j++) { if (vote.optionBitMask & (2**j) == 2**j) { // update voteCounts for each voted option proposal.voteCounts[j] = proposal.voteCounts[j].add(newVotingPower).sub(oldVotingPower); } } // update voting power of the voter _proposals[proposalIds[i]].votes[voter].votingPower = safeNewVotingPower; emit VotingPowerChanged( proposalIds[i], voter, vote.optionBitMask, vote.votingPower, safeNewVotingPower ); } } /** * @dev Transfer dao operator * @param newDaoOperator new dao operator **/ function transferDaoOperator(address newDaoOperator) external { require(msg.sender == _daoOperator, 'only dao operator'); require(newDaoOperator != address(0), 'invalid dao operator'); _daoOperator = newDaoOperator; emit DaoOperatorTransferred(newDaoOperator); } /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] memory executors) public override onlyAdmin { _authorizeExecutors(executors); } /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] memory executors) public override onlyAdmin { _unauthorizeExecutors(executors); } /** * @dev Add new addresses to the list of authorized strategies * @param strategies list of new addresses to be authorized strategies **/ function authorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _authorizeVotingPowerStrategies(strategies); } /** * @dev Remove addresses to the list of authorized strategies * @param strategies list of addresses to be removed as authorized strategies **/ function unauthorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _unauthorizedVotingPowerStrategies(strategies); } /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) public override view returns (bool) { return _authorizedExecutors[executor]; } /** * @dev Returns whether an address is an authorized strategy * @param strategy address to evaluate as authorized strategy * @return true if authorized **/ function isVotingPowerStrategyAuthorized(address strategy) public override view returns (bool) { return _authorizedVotingPowerStrategies[strategy]; } /** * @dev Getter the address of the daoOperator, that can mainly cancel proposals * @return The address of the daoOperator **/ function getDaoOperator() external override view returns (address) { return _daoOperator; } /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external override view returns (uint256) { return _proposalsCount; } /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVote memory object **/ function getProposalById(uint256 proposalId) external override view returns (ProposalWithoutVote memory) { return _proposals[proposalId].proposalData; } /** * @dev Getter of the vote data of a proposal by id * including totalVotes, voteCounts and options * @param proposalId id of the proposal * @return (totalVotes, voteCounts, options) **/ function getProposalVoteDataById(uint256 proposalId) external override view returns ( uint256, uint256[] memory, string[] memory ) { ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; return (proposal.totalVotes, proposal.voteCounts, proposal.options); } /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({uint32 bitOptionMask, uint224 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external override view returns (Vote memory) { return _proposals[proposalId].votes[voter]; } /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) public override view returns (ProposalState) { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp < proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.proposalType == ProposalType.Generic) { return ProposalState.Finalized; } else if ( !IProposalValidator(address(proposal.executor)).isBinaryProposalPassed( IKyberGovernance(this), proposalId ) ) { return ProposalState.Failed; } else if (proposal.executionTime == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (proposal.executor.isProposalOverGracePeriod(this, proposalId)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _queueOrRevert( IExecutorWithTimelock executor, address target, uint256 value, string memory signature, bytes memory callData, uint256 executionTime, bool withDelegatecall ) internal { require( !executor.isActionQueued( keccak256(abi.encode(target, value, signature, callData, executionTime, withDelegatecall)) ), 'duplicated action' ); executor.queueTransaction(target, value, signature, callData, executionTime, withDelegatecall); } function _submitVote( address voter, uint256 proposalId, uint256 optionBitMask ) internal { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Active, 'voting closed'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; uint256 numOptions = proposal.options.length; if (proposal.proposalType == ProposalType.Binary) { // either Yes (1) or No (2) require(optionBitMask == 1 || optionBitMask == 2, 'wrong vote for binary proposal'); } else { require( optionBitMask > 0 && optionBitMask < 2**numOptions, 'invalid options for generic proposal' ); } Vote memory vote = _proposals[proposalId].votes[voter]; uint256 votingPower = proposal.strategy.handleVote(voter, proposalId, optionBitMask); if (vote.optionBitMask == 0) { // first time vote, increase the totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(votingPower); } for (uint256 i = 0; i < proposal.options.length; i++) { bool hasVoted = (vote.optionBitMask & (2**i)) == 2**i; bool isVoting = (optionBitMask & (2**i)) == 2**i; if (hasVoted && !isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].sub(votingPower); } else if (!hasVoted && isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].add(votingPower); } } _proposals[proposalId].votes[voter] = Vote({ optionBitMask: _safeUint32(optionBitMask), votingPower: _safeUint224(votingPower) }); emit VoteEmitted(proposalId, voter, _safeUint32(optionBitMask), _safeUint224(votingPower)); } function _authorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = true; emit ExecutorAuthorized(executors[i]); } } function _unauthorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = false; emit ExecutorUnauthorized(executors[i]); } } function _authorizeVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = true; emit VotingPowerStrategyAuthorized(strategies[i]); } } function _unauthorizedVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = false; emit VotingPowerStrategyUnauthorized(strategies[i]); } } function _safeUint224(uint256 value) internal pure returns (uint224) { require(value < 2**224 - 1, 'value is too big (uint224)'); return uint224(value); } function _safeUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32 - 1, 'value is too big (uint32)'); return uint32(value); } }
Queue the proposal (If Proposal Succeeded), only for Binary proposals proposalId id of the proposal to queue/ generic proposal does not have Succeeded state
function queue(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); require( getProposalState(proposalId) == ProposalState.Succeeded, 'invalid state to queue' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; assert(proposal.proposalType == ProposalType.Binary); uint256 executionTime = block.timestamp.add(proposal.executor.getDelay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.executor, proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], executionTime, proposal.withDelegatecalls[i] ); } proposal.executionTime = executionTime; emit ProposalQueued(proposalId, executionTime, msg.sender); }
5,428,141
pragma solidity ^0.5.2; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyDataInterface.sol"; contract FlightSuretyData is FlightSuretyDataInterface { using SafeMath for uint256; using SafeMath for uint8; /* ============================================================================================== */ /* DATA VARIABLES */ /* ============================================================================================== */ /// Account used to deploy contract address private contractOwner; /// Blocks all state changes throughout the contract if false bool private operational = true; /// List of app contract addresses allowed to call this contract mapping(address => bool) private authorizedContracts; /// Registeration type state RegisterationType private registerationType; /// Number of registered Airlines uint256 private numberOfRegisteredAirlines; /// Number of funded Airlines uint256 private numberOfFundedAirlines; /// List of airlins mapped by its addresses to Airline structure mapping(address => Airline) private airlines; /// Insurance data states mapping(bytes32 => Insurance) private insurances; mapping(bytes32 => bytes32[]) private flightInsuranceKeys; mapping(address => bytes32[]) private passengerInsuranceKeys; /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* EVENT DEFINITIONS */ /* ============================================================================================== */ event OperationalStateToggled(bool operational); event ContractAuthorized(address contractAddress); event ContractDeauthorized(address contractAddress); /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* CONSTRUCTOR&FALLBACK FUNCTION */ /* ============================================================================================== */ /// @dev Constructor /// The deploying account becomes contractOwner and adding first airline constructor() public payable { contractOwner = msg.sender; /// Adding 1st airline addAirline( msg.sender, "SAUDIA", AirlineRegisterationState.Funded ); registerationType = RegisterationType.BY_MEDIATION; numberOfFundedAirlines = 1; } /// @dev Fallback function for funding smart contract. function() external payable { if (msg.value > 10 ether) fund(msg.sender); } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* FUNCTION MODIFIERS */ /* ============================================================================================== */ /// @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 modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } /// @dev Modifier that requires the "ContractOwner" account to be the function caller modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /// @dev Only authorized contract addresses can call this modifier modifier requireCallerAuthorized() { require(authorizedContracts[msg.sender] == true, "Contract Address not authorized to call this function"); _; } /// @dev Modifier that checks if airline address not existing in data modifier requireNotExistAirline(address airlineAddress) { require(!airlines[airlineAddress].isExist, "Cannot register a registered airline address"); _; } /// @dev Modifier that checks if airline address existing in data modifier requireExistAirline(address airlineAddress) { require(airlines[airlineAddress].isExist, "Airline address not existing"); _; } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* PUBLIC UTILITY FUNCTIONS */ /* ============================================================================================== */ /// @dev Get operating status of contract /// @return A boolean that is the current operating status function isOperational() external view returns(bool) { return operational; } /// @dev Get Authorization status of a contract address /// @param contractAddress Ethereum contract address to check /// @return Boolean if its authorized or not function isAuthorized(address contractAddress) external view requireIsOperational returns(bool) { return authorizedContracts[contractAddress]; } /// @dev Get registration type state /// @return Current registration type as `RegisterationType` enum function getRegistrationType() external view requireIsOperational returns(RegisterationType) { return registerationType; } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* OWNER UTILITY FUNCTIONS */ /* ============================================================================================== */ /// @dev Sets contract operations on/off /// When operational mode is disabled, all write transactions except for this one will fail /// @return A boolean for new operating status function toggleOperatingStatus() external requireContractOwner() { operational = !operational; emit OperationalStateToggled(operational); } /// @dev Authoriztion process for new version of app contract /// Only the owner of the contract can authrize a caller contract to start changing data state function authorizeCallerContract(address contractAddress) external requireContractOwner requireIsOperational { require(authorizedContracts[contractAddress] == false, "allready authorized"); authorizedContracts[contractAddress] = true; emit ContractAuthorized(contractAddress); } /// @dev Deauthoriztion process for a version of app contract /// Only the owner of the contract can deauthrize a caller contract function deauthorizeCallerContract(address contractAddress) external requireContractOwner requireIsOperational { require(authorizedContracts[contractAddress] == true, "allready deauthorized"); authorizedContracts[contractAddress] = false; emit ContractDeauthorized(contractAddress); } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* CONTRACT UTILITY FUNCTIONS */ /* ============================================================================================== */ /// @dev Get existing state of an airline address /// @notice Can only be called from authorized contract /// @param airlineAddress Ethereum address of airline to check /// @return Boolean eather its exist or not function isAirlineExist(address airlineAddress) external view requireIsOperational requireCallerAuthorized returns(bool) { return airlines[airlineAddress].isExist; } /// @dev Get an airline registring voter state /// @notice Can only be called from authorized contract /// @param airlineAddress Ethereum address of airline to check /// @param voterAddress Ethereum address of voter to check /// @return Boolean eather its voted or not function isVotedForRegisteringAirline(address airlineAddress, address voterAddress) external view requireIsOperational requireCallerAuthorized returns(bool) { return airlines[airlineAddress].registeringVotes.voters[voterAddress]; } /// @dev Get an airline removing voter state /// @notice Can only be called from authorized contract /// @param airlineAddress Ethereum address of airline to check /// @param voterAddress Ethereum address of voter to check /// @return Boolean eather its voted or not function isVotedForRemovingAirline(address airlineAddress, address voterAddress) external view requireIsOperational requireCallerAuthorized returns(bool) { return airlines[airlineAddress].removingVotes.voters[voterAddress]; } /// @dev Get the number of registered airlines /// @notice Can only be called from authorized contract /// @return Current number of registered airline as `uint256` function getNumberOfRegisteredAirlines() external view requireIsOperational requireCallerAuthorized returns(uint256) { return(numberOfRegisteredAirlines); } /// @dev Get the number of registered and funded airlines /// @return Current number of active airline (funded airline) as `uint256` function getNumberOfActiveAirlines() external view requireIsOperational requireCallerAuthorized returns(uint256) { return(numberOfFundedAirlines); } /// @dev Get airline registration state /// @notice Can only be called from authorized contract /// @param airlineAddress Ethereum address of airline to check /// @return Current registration of airline as `AirlineRegisterationState` enumeration function getAirlineState(address airlineAddress) external view requireIsOperational requireCallerAuthorized requireExistAirline(airlineAddress) returns(AirlineRegisterationState) { return (airlines[airlineAddress].state); } /// @dev Get number of votes for an airline /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account to get its number of votes /// @return Current number of votes for a spicefic airline function getAirlineVotes(address airlineAddress) external view requireIsOperational requireCallerAuthorized requireExistAirline(airlineAddress) returns(uint) { return airlines[airlineAddress].registeringVotes.numberOfVotes; } /// @dev Get registered airline /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account to retrive its data /// @return tuple contain some airline struct data function fetchAirlineData(address airlineAddress) external view requireIsOperational requireCallerAuthorized requireExistAirline(airlineAddress) returns( bool isExist, string memory name, AirlineRegisterationState state, uint numberOfRegistringVotes, uint numberOfRemovingVotes, uint8 failureRate, bytes32[] memory flightKeys, uint numberOfInsurance ) { Airline memory _airline = airlines[airlineAddress]; return( _airline.isExist, _airline.name, _airline.state, _airline.registeringVotes.numberOfVotes, _airline.removingVotes.numberOfVotes, _airline.failureRate, _airline.flightKeys, _airline.numberOfInsurance ); } /// @dev Get insurance data by its key /// @notice Can only be called from authorized contract /// @param insuranceKey Insurance key to fetch its data /// @return tuple contain all Insurance struct data function fetchInsuranceData(bytes32 insuranceKey) external view requireIsOperational requireCallerAuthorized returns( address buyer, address airline, uint value, uint ticketNumber, InsuranceState state ) { Insurance memory _insurance = insurances[insuranceKey]; return( _insurance.buyer, _insurance.airline, _insurance.value, _insurance.ticketNumber, _insurance.state ); } /// @dev Get insurances keys for a flight /// @notice Can only be called from authorized contract /// @param flightKey Key of a flight as bytes32 /// @return array of keys as bytes32 data type function fetchFlightInsurances(bytes32 flightKey) external view requireIsOperational requireCallerAuthorized returns(bytes32[] memory) { return flightInsuranceKeys[flightKey]; } /// @dev Get insurances keys for a passenger(buyer) /// @notice Can only be called from authorized contract /// @param passengerAddress Passenger ethereum account to retrive its keys /// @return array of keys as bytes32 data type function fetchPasengerInsurances(address passengerAddress) external view requireIsOperational requireCallerAuthorized returns(bytes32[] memory) { return passengerInsuranceKeys[passengerAddress]; } /// @dev Set registration type state /// @notice Can only be called from authorized contract /// @param _type Registration type to be the stat of registertion way function setRegistrationType(RegisterationType _type) external requireCallerAuthorized() { registerationType = _type; } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* SMART CONTRACT FUNCTIONS */ /* ============================================================================================== */ /// @dev Register an airline /// @notice Can only be called from authorized contract /// @param airlineAddress Ethereum account owned by airline to be saved /// @param name Airline name (company name) /// @param state Inital state of the airline **it'll be managed in App contract** function registerAirline ( address airlineAddress, string calldata name, AirlineRegisterationState state ) external requireCallerAuthorized() { addAirline( airlineAddress, name, state ); } /// @dev Update exist airline data /// @notice Can only be called from authorized contract /// For future using if needed function updateAirline ( address airlineAddress, bool isExist, string calldata name, AirlineRegisterationState state, uint8 failureRate, bytes32[] calldata flightKeys, uint numberOfInsurance ) external requireCallerAuthorized() requireExistAirline(airlineAddress) { Airline storage _airline = airlines[airlineAddress]; _airline.isExist = isExist; _airline.name = name; _airline.state = state; _airline.failureRate = failureRate; _airline.flightKeys = flightKeys; _airline.numberOfInsurance = numberOfInsurance; } /// @dev Delete existing airline /// For future using if needed function deleteAirline ( address airlineAddress ) external requireCallerAuthorized() requireExistAirline(airlineAddress) { delete airlines[airlineAddress]; } /// @dev Transfer owned airline /// @notice Can only be called from authorized contract /// For future use if needed function transferAirline ( address airlineAddress, address newAirlineAddress ) external requireCallerAuthorized() requireExistAirline(airlineAddress) requireNotExistAirline(newAirlineAddress) { Airline memory _airline = airlines[airlineAddress]; delete airlines[airlineAddress]; airlines[newAirlineAddress] = _airline; } /// @dev Add airline's flight to its structure /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account to add to /// @param flightKey new flight key that added to flight mapping function addFlightKeyToAirline ( address airlineAddress, bytes32 flightKey ) external requireCallerAuthorized() { airlines[airlineAddress].flightKeys.push(flightKey); } /// @dev Set airline state /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account to change its state /// @param _state The new state of airline registeration to be updated function setAirlineState ( address airlineAddress, AirlineRegisterationState _state ) external requireCallerAuthorized() { airlines[airlineAddress].state = _state; } /// @dev Add vote for an airline /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account to add vote to /// @param voterAddress Voter address used to call this function function addAirlineVote(address airlineAddress, address voterAddress) external requireCallerAuthorized() { uint currentNumber = airlines[airlineAddress].registeringVotes.numberOfVotes; airlines[airlineAddress].registeringVotes.voters[voterAddress] = true; airlines[airlineAddress].registeringVotes.numberOfVotes = currentNumber.add(1); } /// @dev Build new single insurance for a flight /// @notice Can only be called from authorized contract /// @param airlineAddress Airline ethereum account used to call theis function /// @param flightKey Key for a flight to add insurance to /// @param ticketNumber Uniqe number for ticket owned produced by airline function buildFlightInsurance ( address airlineAddress, bytes32 flightKey, uint ticketNumber ) external requireCallerAuthorized() { bytes32 insuranceKey = getInsuranceKey(flightKey, ticketNumber); require(insurances[insuranceKey].state == InsuranceState.NotExist, "Ticket number for this flight allready built"); insurances[insuranceKey] = Insurance({ buyer: address(0), airline: airlineAddress, value: 0, ticketNumber: ticketNumber, state: InsuranceState.WaitingForBuyer }); flightInsuranceKeys[flightKey].push(insuranceKey); } /// @dev Buy insurance for a flight /// @notice Can only be called from authorized contract /// @param buyer Pasnnger address used to buy insurance /// @param insuranceKey Insurance key to buy it function buyInsurance ( address buyer, bytes32 insuranceKey ) external payable requireCallerAuthorized() { require(insurances[insuranceKey].state == InsuranceState.WaitingForBuyer, "Insurance allredy bought, or not exist or expired"); insurances[insuranceKey].value = msg.value; insurances[insuranceKey].buyer = buyer; insurances[insuranceKey].state = InsuranceState.Bought; //passengerInsuranceKeys[buyer].push(insuranceKey); } /// @dev Credits payouts to insurees /// @notice Can only be called from authorized contract /// @param flightKey Flight key to update is insurnce /// @param creditRate Rate of credit for insuree out of 100 == 1 function creditInsurees ( bytes32 flightKey, uint8 creditRate ) external requireCallerAuthorized() { bytes32[] storage _insurancesKeys = flightInsuranceKeys[flightKey]; for (uint i = 0; i < _insurancesKeys.length; i++) { Insurance storage _insurance = insurances[_insurancesKeys[i]]; if (_insurance.state == InsuranceState.Bought) { _insurance.value = _insurance.value.mul(creditRate).div(100); if (_insurance.value > 0) _insurance.state = InsuranceState.Passed; else _insurance.state = InsuranceState.Expired; } else { _insurance.state = InsuranceState.Expired; } } } /// @dev Transfers eligible payout funds to insuree /// @notice Can only be called from authorized contract /// @param insuranceKey Insurance key to pay its buyer function payInsuree(bytes32 insuranceKey) external requireCallerAuthorized() { Insurance memory _insurance = insurances[insuranceKey]; require(_insurance.state == InsuranceState.Passed, "no value to withdrow"); require(address(this).balance > _insurance.value, "try again later"); uint _value = _insurance.value; _insurance.value = 0; _insurance.state = InsuranceState.Expired; address payable insuree = address(uint160(_insurance.buyer)); insuree.transfer(_value); } /// @dev Initial funding for the insurance. function fund(address funder) public payable { require(airlines[funder].state == AirlineRegisterationState.Registered, "Airline address not registered yet!"); numberOfFundedAirlines = numberOfFundedAirlines.add(1); airlines[funder].state = AirlineRegisterationState.Funded; } /* ---------------------------------------------------------------------------------------------- */ /* ============================================================================================== */ /* PRIVATE CONTRACT FUNCTIONS */ /* ============================================================================================== */ /// @dev Internally Add new airline intety to data mapping /// @param account The airline account address to be added /// @param name The airline company name /// @param state Whiche state will be assign when added airline function addAirline ( address account, string memory name, AirlineRegisterationState state ) private { numberOfRegisteredAirlines = numberOfRegisteredAirlines.add(1); airlines[account] = Airline({ isExist: true, name: name, state: state, failureRate: 0, registeringVotes: Votes(0), removingVotes: Votes(0), flightKeys: new bytes32[](0), numberOfInsurance: 0 }); } /// @dev Internally helper function to get flight key /// @notice This function is pure make sure to handle existing of airline and flight when using returned key /// @param airline Address of airline /// @param flight The name of flight as string data type /// @param timestamp Depurture time of the flight as uint data type /// @return Key as static array of 32 bytes to make it uniqe function getFlightKey ( address airline, string memory flight, uint256 timestamp ) private pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /// @dev Internally helper function to get insurance key /// @notice This function is pure make sure to handle existing of airline, flight and insurance when using returned key /// @param flightKey Address of airline /// @param ticketNumber Uniqe number for ticket owned by one passanger /// @return Key as static array of 32 bytes to make it uniqe function getInsuranceKey ( bytes32 flightKey, uint ticketNumber ) private pure returns(bytes32) { return keccak256(abi.encodePacked(flightKey, ticketNumber)); } /* ---------------------------------------------------------------------------------------------- */ }
Get airline registration state Can only be called from authorized contract airlineAddress Ethereum address of airline to check return Current registration of airline as `AirlineRegisterationState` enumeration
function getAirlineState(address airlineAddress) external view requireIsOperational requireCallerAuthorized requireExistAirline(airlineAddress) returns(AirlineRegisterationState) { return (airlines[airlineAddress].state); }
12,960,000
./full_match/1/0x873847b829a33C87c1fb227367D7b28a7DF979b4/sources/contracts/radiant/staking/ChefIncentivesController.sol
Vest tokens to MFD. _user address to receive _amount to vest/
function _vestTokens(address _user, uint256 _amount) internal { if (_amount == 0) revert NothingToVest(); IMultiFeeDistribution mfd = _getMfd(); _sendRadiant(address(mfd), _amount); mfd.vestTokens(_user, _amount, true); }
3,223,443
// SPDX-License-Identifier: MIT /* * Plug.sol * * Author: Jack Kasbeer * Created: August 3, 2021 * * Price: 0.0888 ETH * Rinkeby: 0xf9d798514eb5eA645C90D8633FcC3DA17da8288e * * Description: An ERC-721 token that will change based on (1) time held by a single owner and * (2) trades between owners; the different versions give you access to airdrops. * * - As long as the owner remains the same, every 60 days, the asset will acquire more "juice" * not only updating the asset, but allowing the owner to receive more airdrops from other * artists. This means after a year, the final asset (and most valuable) will now be in the * owner's wallet (naturally each time, the previous asset is replaced). * - If the NFT changes owners, the initial/day 0 asset is now what will be seen by the owner, * and they'll have to wait a full cycle "final asset status" (gold) * - If a Plug is a Alchemist (final state), it means that it will never lose juice again, * even if it is transferred. */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Kasbeer721.sol"; //@title The Plug //@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat) contract Plug is Kasbeer721 { using Counters for Counters.Counter; using SafeMath for uint256; //@dev Emitted when token is transferred event PlugTransferred(address indexed from, address indexed to); //@dev How we keep track of how many days a person has held a Plug mapping(uint256 => uint) internal _birthdays; //tokenID -> UTCTime constructor() Kasbeer721("the Plug", "PLUG") { whitelistActive = true; contractUri = "ipfs://QmYUDei8kuEHrPTyEMrWDQSLEtQwzDS16bpFwZab6RZN5j"; payoutAddress = 0x6b8C6E15818C74895c31A1C91390b3d42B336799;//logik _squad[payoutAddress] = true; addToWhitelist(payoutAddress); } // ----------- // RESTRICTORS // ----------- modifier batchLimit(uint256 numToMint) { require(1 <= numToMint && numToMint <= 8, "Plug: mint between 1 and 8"); _; } modifier plugsAvailable(uint256 numToMint) { require(_tokenIds.current() + numToMint <= MAX_NUM_TOKENS, "Plug: not enough Plugs remaining to mint"); _; } modifier tokenExists(uint256 tokenId) { require(_exists(tokenId), "Plug: nonexistent token"); _; } // ---------- // PLUG MAGIC // ---------- //@dev Override 'tokenURI' to account for asset/hash cycling function tokenURI(uint256 tokenId) tokenExists(tokenId) public view virtual override returns (string memory) { string memory baseURI = _baseURI(); string memory hash = _tokenHash(tokenId); return string(abi.encodePacked(baseURI, hash)); } //@dev Based on the number of days that have passed since the last transfer of // ownership, this function returns the appropriate IPFS hash function _tokenHash(uint256 tokenId) internal virtual view returns (string memory) { if (!_exists(tokenId)) { return "";//not a require statement to avoid errors being thrown } // Calculate days gone by for this particular token uint daysPassed = countDaysPassed(tokenId); // Based on the number of days that have gone by, return the appropriate state of the Plug if (daysPassed >= 557) { if (tokenId <= 176) { return chiHashes[7]; } else if (tokenId % 88 == 0) { return stlHashes[7]; } else { return normHashes[7]; } } else if (daysPassed >= 360) { if (tokenId <= 176) { return chiHashes[6]; } else if (tokenId % 88 == 0) { return stlHashes[6]; } else { return normHashes[6]; } } else if (daysPassed >= 300) { if (tokenId <= 176) { return chiHashes[5]; } else if (tokenId % 88 == 0) { return stlHashes[5]; } else { return normHashes[5]; } } else if (daysPassed >= 240) { if (tokenId <= 176) { return chiHashes[4]; } else if (tokenId % 88 == 0) { return stlHashes[4]; } else { return normHashes[4]; } } else if (daysPassed >= 180) { if (tokenId <= 176) { return chiHashes[3]; } else if (tokenId % 88 == 0) { return stlHashes[3]; } else { return normHashes[3]; } } else if (daysPassed >= 120) { if (tokenId <= 176) { return chiHashes[2]; } else if (tokenId % 88 == 0) { return stlHashes[2]; } else { return normHashes[2]; } } else if (daysPassed >= 60) { if (tokenId <= 176) { return chiHashes[1]; } else if (tokenId % 88 == 0) { return stlHashes[1]; } else { return normHashes[1]; } } else { //if 60 days haven't passed, the initial asset/Plug is returned if (tokenId <= 176) { return chiHashes[0]; } else if (tokenId % 88 == 0) { return stlHashes[0]; } else { return normHashes[0]; } } } //@dev Any Plug transfer this will be called beforehand (updating the transfer time) // If a Plug is now an Alchemist, it's timestamp won't be updated so that it never loses juice function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { // If the "1.5 years" have passed, don't change birthday if (_exists(tokenId) && countDaysPassed(tokenId) < 557) { _setBirthday(tokenId); } emit PlugTransferred(from, to); } //@dev Set the last transfer time for a tokenId function _setBirthday(uint256 tokenId) private { _birthdays[tokenId] = block.timestamp; } //@dev List the owners for a certain level (determined by _assetHash) // We'll need this for airdrops and benefits function listPlugOwnersForHash(string memory assetHash) public view returns (address[] memory) { require(_hashExists(assetHash), "Plug: nonexistent hash"); address[] memory levelOwners = new address[](MAX_NUM_TOKENS); uint16 tokenId; uint16 counter; for (tokenId = 1; tokenId <= _tokenIds.current(); tokenId++) { if (_stringsEqual(_tokenHash(tokenId), assetHash)) { levelOwners[counter] = ownerOf(tokenId); counter++; } } return levelOwners; } //@dev List the owners of a category of the Plug (Nomad, Chicago, or St. Louis) function listPlugOwnersForType(uint8 group) groupInRange(group) public view returns (address[] memory) { address[] memory typeOwners = new address[](MAX_NUM_TOKENS); uint16 tokenId; uint16 counter; if (group == 0) { //nomad for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 != 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } else if (group == 1) { //chicago for (tokenId = 1; tokenId <= 176; tokenId++) { if (_exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } else { //st. louis for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 == 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } return typeOwners; } // -------------------- // MINTING & PURCHASING // -------------------- //@dev Allows owners to mint for free function mint(address to) isSquad public virtual override returns (uint256) { return _mintInternal(to); } //@dev Purchase & mint multiple Plugs function purchase( address payable to, uint256 numToMint ) whitelistDisabled batchLimit(numToMint) plugsAvailable(numToMint) public payable returns (bool) { require(msg.value >= numToMint * TOKEN_WEI_PRICE, "Plug: not enough ether"); //send change if too much was sent if (msg.value > 0) { uint256 diff = msg.value.sub(TOKEN_WEI_PRICE * numToMint); if (diff > 0) { to.transfer(diff); } } uint8 i;//mint `numToMint` Plugs to address `to` for (i = 0; i < numToMint; i++) { _mintInternal(to); } return true; } //@dev A whitelist controlled version of `purchaseMultiple` function whitelistPurchase( address payable to, uint256 numToMint ) whitelistEnabled onlyWhitelist(to) batchLimit(numToMint) plugsAvailable(numToMint) public payable returns (bool) { require(msg.value >= numToMint * TOKEN_WEI_PRICE, "Plug: not enough ether"); //send change if too much was sent if (msg.value > 0) { uint256 diff = msg.value.sub(TOKEN_WEI_PRICE * numToMint); if (diff > 0) { to.transfer(diff); } } uint8 i;//mint `_num` Plugs to address `_to` for (i = 0; i < numToMint; i++) { _mintInternal(to); } return true; } //@dev Mints a single Plug & sets up the initial birthday function _mintInternal(address to) plugsAvailable(1) internal virtual returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); _setBirthday(newId); emit ERC721Minted(newId); return newId; } // ---- // TIME // ---- //@dev Returns number of days that have passed since transfer/mint function countDaysPassed(uint256 tokenId) tokenExists(tokenId) public view returns (uint256) { return uint256((block.timestamp - _birthdays[tokenId]) / 1 days); } } // 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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT /* * Kasbeer721.sol * * Author: Jack Kasbeer * Created: August 21, 2021 */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./KasbeerStorage.sol"; import "./KasbeerAccessControl.sol"; import "./LibPart.sol"; //@title Kasbeer Made Contract for an ERC721 //@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat) contract Kasbeer721 is ERC721, KasbeerAccessControl, KasbeerStorage { using Counters for Counters.Counter; using SafeMath for uint256; event ERC721Minted(uint256 indexed tokenId); event ERC721Burned(uint256 indexed tokenId); constructor(string memory temp_name, string memory temp_symbol) ERC721(temp_name, temp_symbol) { // Add my personal address & sender _squad[msg.sender] = true; _squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true; addToWhitelist(0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b); } // ----------- // RESTRICTORS // ----------- modifier hashIndexInRange(uint8 idx) { require(0 <= idx && idx < NUM_ASSETS, "Kasbeer721: index OOB"); _; } modifier groupInRange(uint8 group) { require(0 <= group && group <= 2, "Kasbeer721: group OOB"); _;// 0:nomad, 1:chicago, 2:st.louis } modifier onlyValidTokenId(uint256 tokenId) { require(1 <= tokenId && tokenId <= MAX_NUM_TOKENS, "KasbeerMade721: tokenId OOB"); _; } // ------ // ERC721 // ------ //@dev All of the asset's will be pinned to IPFS function _baseURI() internal view virtual override returns (string memory) { return "ipfs://";//NOTE: per OpenSea recommendations } //@dev This is here as a reminder to override for custom transfer functionality function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); } //@dev Allows owners to mint for free function mint(address to) isSquad public virtual returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(to, newId); emit ERC721Minted(newId); return newId; } //@dev Custom burn function - nothing special function burn(uint256 tokenId) public virtual { require(isInSquad(msg.sender) || msg.sender == ownerOf(tokenId), "Kasbeer721: not owner or in squad."); _burn(tokenId); emit ERC721Burned(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACE_ID_ERC165 || interfaceId == _INTERFACE_ID_ROYALTIES || interfaceId == _INTERFACE_ID_ERC721 || interfaceId == _INTERFACE_ID_ERC721_METADATA || interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE || interfaceId == _INTERFACE_ID_EIP2981 || super.supportsInterface(interfaceId); } // ---------------------- // IPFS HASH MANIPULATION // ---------------------- //@dev Get the hash stored at `idx` for `group` function getHashByIndex( uint8 group, uint8 idx ) groupInRange(group) hashIndexInRange(idx) public view returns (string memory) { if (group == 0) { return normHashes[idx]; } else if (group == 1) { return chiHashes[idx]; } else { return stlHashes[idx]; } } //@dev Allows us to update the IPFS hash values (one at a time) function updateHash( uint8 group, uint8 hashNum, string memory str ) isSquad groupInRange(group) hashIndexInRange(hashNum) public { if (group == 0) { normHashes[hashNum] = str; } else if (group == 1) { chiHashes[hashNum] = str; } else { stlHashes[hashNum] = str; } } //@dev Determine if '_assetHash' is one of the IPFS hashes in asset hashes function _hashExists(string memory assetHash) internal view returns (bool) { uint8 i; for (i = 0; i < NUM_ASSETS; i++) { if (_stringsEqual(assetHash, normHashes[i]) || _stringsEqual(assetHash, chiHashes[i]) || _stringsEqual(assetHash, stlHashes[i])) { return true; } } return false; } // ------ // USEFUL // ------ //@dev Returns the current token id (number minted so far) function getCurrentId() public view returns (uint256) { return _tokenIds.current(); } //@dev Allows us to withdraw funds collected function withdraw(address payable wallet, uint256 amount) isSquad public { require(amount <= address(this).balance, "Kasbeer721: Insufficient funds to withdraw"); wallet.transfer(amount); } //@dev Destroy contract and reclaim leftover funds function kill() onlyOwner public { selfdestruct(payable(msg.sender)); } // ------------ // CONTRACT URI // ------------ //@dev Controls the contract-level metadata to include things like royalties function contractURI() public view returns(string memory) { return contractUri; } //@dev Ability to change the contract URI function updateContractUri(string memory updatedContractUri) isSquad public { contractUri = updatedContractUri; } // ----------------- // SECONDARY MARKETS // ----------------- //@dev Rarible Royalties V2 function getRaribleV2Royalties(uint256 id) onlyValidTokenId(id) external view returns (LibPart.Part[] memory) { LibPart.Part[] memory royalties = new LibPart.Part[](1); royalties[0] = LibPart.Part({ account: payable(payoutAddress), value: uint96(royaltyFeeBps) }); return royalties; } //@dev EIP-2981 function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) { uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000); return (payoutAddress, ourCut); } // ------- // HELPERS // ------- //@dev Determine if two strings are equal using the length + hash method function _stringsEqual(string memory a, string memory b) internal pure returns (bool) { bytes memory A = bytes(a); bytes memory B = bytes(b); if (A.length != B.length) { return false; } else { return keccak256(A) == keccak256(B); } } } // 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 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 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 /* * KasbeerStorage.sol * * Author: Jack Kasbeer * Created: August 21, 2021 */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/utils/Counters.sol"; //@title A storage contract for relevant data //@author Jack Kasbeer (@jcksber, @satoshigoat) contract KasbeerStorage { //@dev These take care of token id incrementing using Counters for Counters.Counter; Counters.Counter internal _tokenIds; uint256 constant public royaltyFeeBps = 1500; // 15% bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a; bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca; //@dev Important numbers uint constant NUM_ASSETS = 8; uint constant MAX_NUM_TOKENS = 888; uint constant TOKEN_WEI_PRICE = 88800000000000000;//0.0888 ETH //@dev Properties string internal contractUri; address public payoutAddress; //@dev Initial production hashes //Our list of IPFS hashes for each of the "Nomad" 8 Plugs (varying juice levels) string [NUM_ASSETS] normHashes = ["QmZzB15bPgTqyHzULMFK1jNdbbDGVGCX4PJNbyGGMqLCjL", "QmeXZGeywxRRDK5mSBHNVnUzGv7Kv2ATfLHydPfT5LpbZr", "QmYTf2HE8XycQD9uXshiVtXqNedS83WycJvS2SpWAPfx5b", "QmYXjEkeio2nbMqy3DA7z2LwYFDyq1itbzdujGSoCsFwpN", "QmWmvRqpT59QU9rDT28fiKgK6g8vUjRD2TSSeeBPr9aBNm", "QmWtMb73QgSgkL7mY8PQEt6tgufMovXWF8ecurp2RD7X6R", "Qmbd4uEwtPBfw1XASkgPijqhZDL2nZcRwPbueYaETuAfGt", "QmayAeQafrWUHV3xb8DnXTGLn97xnh7X2Z957Ss9AtfkAD"]; //Our list of IPFS hashes for each of the "Chicago" 8 Plugs (varying juice levels) string [NUM_ASSETS] chiHashes = ["QmNsSUji2wX4E8xmv8vynmSUCACPdCh7NznVSGMQ3hwLC3", "QmYPq4zFLyREaZsPwZzXB3w94JVYdgFHGgRAuM6CK6PMes", "QmbrATHXTkiyNijkfQcEMGT7ujpunsoLNTaupMYW922jp3", "QmWaj5VHcBXgAQnct88tbthVmv1ecX7ft2aGGqMAt4N52p", "QmTyFgbJXX2vUCZSjraKubXfE4NVr4nVrKtg3GK4ysscDX", "QmQxQoAe47CUXtGY9NTA6dRgTJuDtM4HDqz9kW2UK1VHtU", "QmaXYexRBrbr6Uv89cGyWXWCbyaoQDhy3hHJuktSTWFXtJ", "QmeSQdMYLECcSfCSkMenPYuNL2v42YQEEA4HJiP36Zn7Z6"]; //Our list of IPFS hashes for each of the "Chicago" 8 Plugs (varying juice levels) string [NUM_ASSETS] stlHashes = ["QmcB5AqhpNA8o5RT3VTeDsqNBn6VGEaXzeTKuomakTNueM", "QmcjP9d54RcmPXgGt6XxNavr7dtQDAhAnatKjJ5a1Bqbmc", "QmV3uFvGgGQdN4Ub81LWVnp3qjwMpKDvVwQmBzBNzAjWxB", "Qmc3fWuQTxAgsBYK2g4z5VrK47nvfCrWHFNa5zA8DDoUbs", "QmWRPStH4RRMrFzAJcTs2znP7hbVctbLHPUvEn9vXWSTfk", "QmVobnLvtSvgrWssFyWAPCUQFvKsonRMYMYRQPsPSaQHTK", "QmQvGuuRgKxqTcAA7xhGdZ5u2EzDKvWGYb1dMXz2ECwyZi", "QmdurJn1GYVz1DcNgqbMTqnCKKFxpjsFuhoS7bnfBp2YGk"]; } // SPDX-License-Identifier: MIT /* * KasbeerAccessControl.sol * * Author: Jack Kasbeer * Created: October 14, 2021 * * This is an extension of `Ownable` to allow a larger set of addresses to have * certain control in the inheriting contracts. */ pragma solidity >=0.5.16 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract KasbeerAccessControl is Ownable { // ----- // SQUAD // ----- //@dev Ownership - list of squad members (owners) mapping (address => bool) internal _squad; //@dev Custom "approved" modifier because I don't like that language modifier isSquad() { require(isInSquad(msg.sender), "KasbeerAccessControl: Caller not part of squad."); _; } //@dev Determine if address `a` is an approved owner function isInSquad(address a) public view returns (bool) { return _squad[a]; } //@dev Add `a` to the squad function addToSquad(address a) onlyOwner public { require(!isInSquad(a), "KasbeerAccessControl: Address already in squad."); _squad[a] = true; } //@dev Remove `a` from the squad function removeFromSquad(address a) onlyOwner public { require(isInSquad(a), "KasbeerAccessControl: Address already not in squad."); _squad[a] = false; } // --------- // WHITELIST // --------- //@dev Whitelist mapping for client addresses mapping (address => bool) internal _whitelist; //@dev Whitelist flag for active/inactive states bool whitelistActive; //@dev Determine if someone is in the whitelsit modifier onlyWhitelist(address a) { require(isInWhitelist(a)); _; } //@dev Prevent non-whitelist minting functions from being used // if `whitelistActive` == 1 modifier whitelistDisabled() { require(whitelistActive == false, "KasbeerAccessControl: whitelist still active"); _; } //@dev Require that the whitelist is currently enabled modifier whitelistEnabled() { require(whitelistActive == true, "KasbeerAccessControl: whitelist not active"); _; } //@dev Turn the whitelist on function activateWhitelist() isSquad whitelistDisabled public { whitelistActive = true; } //@dev Turn the whitelist off function deactivateWhitelist() isSquad whitelistEnabled public { whitelistActive = false; } //@dev Prove that one of our whitelist address owners has been approved function isInWhitelist(address a) public view returns (bool) { return _whitelist[a]; } //@dev Add a single address to whitelist function addToWhitelist(address a) isSquad public { require(!isInWhitelist(a), "KasbeerAccessControl: already whitelisted"); //here we care if address already whitelisted to save on gas fees _whitelist[a] = true; } //@dev Remove a single address from the whitelist function removeFromWhitelist(address a) isSquad public { require(isInWhitelist(a), "KasbeerAccessControl: not in whitelist"); _whitelist[a] = false; } //@dev Add a list of addresses to the whitelist function bulkAddToWhitelist(address[] memory addys) isSquad public { require(addys.length > 1, "KasbeerAccessControl: use `addToWhitelist` instead"); uint8 i; for (i = 0; i < addys.length; i++) { if (!_whitelist[addys[i]]) { _whitelist[addys[i]] = true; } } } } // SPDX-License-Identifier: MIT /* * LibPart.sol * * Author: Jack Kasbeer (token from 'dot') * Created: October 20, 2021 */ pragma solidity >=0.5.16 <0.9.0; //@dev We need this libary for Rarible library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // 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 "../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); } }
List the owners of a category of the Plug (Nomad, Chicago, or St. Louis)nomadchicagost. louis
function listPlugOwnersForType(uint8 group) groupInRange(group) public view returns (address[] memory) { address[] memory typeOwners = new address[](MAX_NUM_TOKENS); uint16 tokenId; uint16 counter; if (group == 0) { for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 != 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } for (tokenId = 1; tokenId <= 176; tokenId++) { if (_exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } for (tokenId = 177; tokenId <= MAX_NUM_TOKENS; tokenId++) { if (tokenId % 88 == 0 && _exists(tokenId)) { typeOwners[counter] = ownerOf(tokenId); counter++; } } } return typeOwners; }
12,630,931
// SPDX-License-Identifier: MIT @GoPocketStudio pragma solidity ^0.7.5; pragma abicoder v2; interface IERC1155 { function balanceOf(address account, uint256 id) external view returns (uint256); } interface IERC721 { function ownerOf(uint256 tokenId) external view returns (address owner); } contract NFTBalanceChecker { /* Fallback function, don't accept any ETH */ receive() external payable { // revert(); revert("BalanceChecker does not accept payments"); } function isContract(address token) public view returns(bool){ // check if token is actually a contract uint256 tokenCode; assembly { tokenCode := extcodesize(token) } // contract code size return tokenCode > 0; } function balances(address[] memory users, address[] memory tokens, uint256[] memory ids) external view returns (uint[] memory) { uint[] memory addrBalances = new uint[](tokens.length * users.length); for (uint i = 0; i < users.length; i++) { for (uint j = 0; j < tokens.length; j++) { uint addrIdx = j + tokens.length * i; if (isContract(tokens[j])) { IERC1155 t = IERC1155(tokens[j]); addrBalances[addrIdx] = t.balanceOf(users[i], ids[j]); } else { addrBalances[addrIdx] = 0; } } } return addrBalances; } function owners(address[] memory users, address[] memory tokens, uint256[] memory ids) external view returns (address[] memory) { address[] memory addrBalances = new address[](tokens.length * users.length); for (uint i = 0; i < users.length; i++) { for (uint j = 0; j < tokens.length; j++) { uint addrIdx = j + tokens.length * i; if (isContract(tokens[j])) { IERC721 t = IERC721(tokens[j]); addrBalances[addrIdx] = t.ownerOf(ids[j]); } else { addrBalances[addrIdx] = address(0x0); } } } return addrBalances; } }
check if token is actually a contract
function isContract(address token) public view returns(bool){ uint256 tokenCode; return tokenCode > 0; }
1,463,690
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OpenZeppelin/access/Ownable.sol"; import "./OpenZeppelin/utils/Pausable.sol"; import "./OpenZeppelin/token/ERC721/ERC721.sol"; import "./OpenZeppelin/token/ERC721/ERC721Holder.sol"; import "./Settings.sol"; import "./ERC721TokenVault.sol"; contract ERC721VaultFactory is Ownable, Pausable { /// @notice the number of ERC721 vaults uint256 public vaultCount; /// @notice the mapping of vault number to vault contract mapping(uint256 => TokenVault) public vaults; /// @notice a settings contract controlled by governance address public settings; event Mint(address indexed token, uint256 id, uint256 price, address vault, uint256 vaultId); constructor(address _settings) { settings = _settings; } /// @notice the function to mint a new vault /// @param _name the desired name of the vault /// @param _symbol the desired sumbol of the vault /// @param _token the ERC721 token address fo the NFT /// @param _id the uint256 ID of the token /// @param _listPrice the initial price of the NFT /// @return the ID of the vault function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external whenNotPaused returns(uint256) { TokenVault vault = new TokenVault(settings, msg.sender, _token, _id, _supply, _listPrice, _fee, _name, _symbol); emit Mint(_token, _id, _listPrice, address(vault), vaultCount); IERC721(_token).safeTransferFrom(msg.sender, address(vault), _id); vaults[vaultCount] = vault; vaultCount++; return vaultCount - 1; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.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 Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // 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; /** * @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_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(type(IERC721).interfaceId); _registerInterface(type(IERC721Metadata).interfaceId); _registerInterface(type(IERC721Enumerable).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 _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()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.0; import "./OpenZeppelin/access/Ownable.sol"; import "./Interfaces/ISettings.sol"; contract Settings is Ownable, ISettings { /// @notice the maximum auction length uint256 public override maxAuctionLength; /// @notice the longest an auction can ever be uint256 public constant maxMaxAuctionLength = 8 weeks; /// @notice the minimum auction length uint256 public override minAuctionLength; /// @notice the shortest an auction can ever be uint256 public constant minMinAuctionLength = 1 days; /// @notice governance fee max uint256 public override governanceFee; /// @notice 10% fee is max uint256 public constant maxGovFee = 100; /// @notice max curator fee uint256 public override maxCuratorFee; /// @notice the % bid increase required for a new bid uint256 public override minBidIncrease; /// @notice 10% bid increase is max uint256 public constant maxMinBidIncrease = 100; /// @notice 1% bid increase is min uint256 public constant minMinBidIncrease = 10; /// @notice the % of tokens required to be voting for an auction to start uint256 public override minVotePercentage; /// @notice the max % increase over the initial uint256 public override maxReserveFactor; /// @notice the max % decrease from the initial uint256 public override minReserveFactor; /// @notice the address who receives auction fees address payable public override feeReceiver; event UpdateMaxAuctionLength(uint256 _old, uint256 _new); event UpdateMinAuctionLength(uint256 _old, uint256 _new); event UpdateGovernanceFee(uint256 _old, uint256 _new); event UpdateCuratorFee(uint256 _old, uint256 _new); event UpdateMinBidIncrease(uint256 _old, uint256 _new); event UpdateMinVotePercentage(uint256 _old, uint256 _new); event UpdateMaxReserveFactor(uint256 _old, uint256 _new); event UpdateMinReserveFactor(uint256 _old, uint256 _new); event UpdateFeeReceiver(address _old, address _new); constructor() { maxAuctionLength = 2 weeks; minAuctionLength = 3 days; feeReceiver = payable(msg.sender); minReserveFactor = 500; // 50% maxReserveFactor = 2000; // 200% minBidIncrease = 50; // 5% maxCuratorFee = 100; minVotePercentage = 500; // 50% } function setMaxAuctionLength(uint256 _length) external onlyOwner { require(_length <= maxMaxAuctionLength, "max auction length too high"); require(_length > minAuctionLength, "max auction length too low"); emit UpdateMaxAuctionLength(maxAuctionLength, _length); maxAuctionLength = _length; } function setMinAuctionLength(uint256 _length) external onlyOwner { require(_length >= minMinAuctionLength, "min auction length too low"); require(_length < maxAuctionLength, "min auction length too high"); emit UpdateMinAuctionLength(minAuctionLength, _length); minAuctionLength = _length; } function setGovernanceFee(uint256 _fee) external onlyOwner { require(_fee <= maxGovFee, "fee too high"); emit UpdateGovernanceFee(governanceFee, _fee); governanceFee = _fee; } function setMaxCuratorFee(uint256 _fee) external onlyOwner { emit UpdateCuratorFee(governanceFee, _fee); maxCuratorFee = _fee; } function setMinBidIncrease(uint256 _min) external onlyOwner { require(_min <= maxMinBidIncrease, "min bid increase too high"); require(_min >= minMinBidIncrease, "min bid increase too low"); emit UpdateMinBidIncrease(minBidIncrease, _min); minBidIncrease = _min; } function setMinVotePercentage(uint256 _min) external onlyOwner { // 1000 is 100% require(_min <= 1000, "min vote percentage too high"); emit UpdateMinVotePercentage(minVotePercentage, _min); minVotePercentage = _min; } function setMaxReserveFactor(uint256 _factor) external onlyOwner { require(_factor > minReserveFactor, "max reserve factor too low"); emit UpdateMaxReserveFactor(maxReserveFactor, _factor); maxReserveFactor = _factor; } function setMinReserveFactor(uint256 _factor) external onlyOwner { require(_factor < maxReserveFactor, "min reserve factor too high"); emit UpdateMinReserveFactor(minReserveFactor, _factor); minReserveFactor = _factor; } function setFeeReceiver(address payable _receiver) external onlyOwner { require(_receiver != address(0), "fees cannot go to 0 address"); emit UpdateFeeReceiver(feeReceiver, _receiver); feeReceiver = _receiver; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Interfaces/IWETH.sol"; import "./OpenZeppelin/math/Math.sol"; import "./OpenZeppelin/token/ERC20/ERC20.sol"; import "./OpenZeppelin/token/ERC721/ERC721.sol"; import "./OpenZeppelin/token/ERC721/ERC721Holder.sol"; import "./Settings.sol"; contract TokenVault is ERC20, ERC721Holder { using Address for address; /// ----------------------------------- /// -------- BASIC INFORMATION -------- /// ----------------------------------- /// @notice weth address address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// ----------------------------------- /// -------- TOKEN INFORMATION -------- /// ----------------------------------- /// @notice the ERC721 token address of the vault's token address public token; /// @notice the ERC721 token ID of the vault's token uint256 public id; /// ------------------------------------- /// -------- AUCTION INFORMATION -------- /// ------------------------------------- /// @notice the unix timestamp end time of the token auction uint256 public auctionEnd; /// @notice the length of auctions uint256 public auctionLength; /// @notice reservePrice * votingTokens uint256 public reserveTotal; /// @notice the current price of the token during an auction uint256 public livePrice; /// @notice the current user winning the token auction address payable public winning; enum State { inactive, live, ended, redeemed } State public auctionState; /// ----------------------------------- /// -------- VAULT INFORMATION -------- /// ----------------------------------- /// @notice the governance contract which gets paid in ETH address public settings; /// @notice the address who initially deposited the NFT address public curator; /// @notice the AUM fee paid to the curator yearly. 3 decimals. ie. 100 = 10% uint256 public fee; /// @notice the last timestamp where fees were claimed uint256 public lastClaimed; /// @notice a boolean to indicate if the vault has closed bool public vaultClosed; /// @notice the number of ownership tokens voting on the reserve price at any given time uint256 public votingTokens; /// @notice a mapping of users to their desired token price mapping(address => uint256) public userPrices; /// ------------------------ /// -------- EVENTS -------- /// ------------------------ /// @notice An event emitted when a user updates their price event PriceUpdate(address indexed user, uint price); /// @notice An event emitted when an auction starts event Start(address indexed buyer, uint price); /// @notice An event emitted when a bid is made event Bid(address indexed buyer, uint price); /// @notice An event emitted when an auction is won event Won(address indexed buyer, uint price); /// @notice An event emitted when someone redeems all tokens for the NFT event Redeem(address indexed redeemer); /// @notice An event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale event Cash(address indexed owner, uint256 shares); constructor(address _settings, address _curator, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee, string memory _name, string memory _symbol) ERC20(_name, _symbol) { settings = _settings; token = _token; id = _id; reserveTotal = _listPrice * _supply; auctionLength = 7 days; curator = _curator; fee = _fee; lastClaimed = block.timestamp; votingTokens = _supply; auctionState = State.inactive; _mint(_curator, _supply); userPrices[_curator] = _listPrice; } /// -------------------------------- /// -------- VIEW FUNCTIONS -------- /// -------------------------------- function reservePrice() public view returns(uint256) { return votingTokens == 0 ? 0 : reserveTotal / votingTokens; } /// ------------------------------- /// -------- GOV FUNCTIONS -------- /// ------------------------------- /// @notice allow governance to boot a bad actor curator /// @param _curator the new curator function kickCurator(address _curator) external { require(msg.sender == Ownable(settings).owner(), "kick:not gov"); curator = _curator; } /// ----------------------------------- /// -------- CURATOR FUNCTIONS -------- /// ----------------------------------- /// @notice allow curator to update the curator address /// @param _curator the new curator function updateCurator(address _curator) external { require(msg.sender == curator, "update:not curator"); curator = _curator; } /// @notice allow curator to update the auction length /// @param _length the new base price function updateAuctionLength(uint256 _length) external { require(msg.sender == curator, "update:not curator"); require(_length >= ISettings(settings).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(), "update:invalid auction length"); auctionLength = _length; } /// @notice allow the curator to change their fee /// @param _fee the new fee function updateFee(uint256 _fee) external { require(msg.sender == curator, "update:not curator"); require(_fee <= ISettings(settings).maxCuratorFee(), "update:cannot increase fee this high"); _claimFees(); fee = _fee; } /// @notice external function to claim fees for the curator and governance function claimFees() external { _claimFees(); } /// @dev interal fuction to calculate and mint fees function _claimFees() internal { require(auctionState != State.ended, "claim:cannot claim after auction ends"); // get how much in fees the curator would make in a year uint256 currentAnnualFee = fee * totalSupply() / 1000; // get how much that is per second; uint256 feePerSecond = currentAnnualFee / 31536000; // get how many seconds they are eligible to claim uint256 sinceLastClaim = block.timestamp - lastClaimed; // get the amount of tokens to mint uint256 curatorMint = sinceLastClaim * feePerSecond; // now lets do the same for governance address govAddress = ISettings(settings).feeReceiver(); uint256 govFee = ISettings(settings).governanceFee(); currentAnnualFee = govFee * totalSupply() / 1000; feePerSecond = currentAnnualFee / 31536000; uint256 govMint = sinceLastClaim * feePerSecond; lastClaimed = block.timestamp; _mint(curator, curatorMint); _mint(govAddress, govMint); } /// -------------------------------- /// -------- CORE FUNCTIONS -------- /// -------------------------------- /// @notice a function for an end user to update their desired sale price /// @param _new the desired price in ETH function updateUserPrice(uint256 _new) external { require(auctionState == State.inactive, "update:auction live cannot update price"); uint256 old = userPrices[msg.sender]; require(_new != old, "update:not an update"); uint256 weight = balanceOf(msg.sender); if (votingTokens == 0) { votingTokens = weight; reserveTotal = weight * _new; } // they are the only one voting else if (weight == votingTokens && old != 0) { reserveTotal = weight * _new; } // previously they were not voting else if (old == 0) { uint256 averageReserve = reserveTotal / votingTokens; uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; require(_new >= reservePriceMin, "update:reserve price too low"); uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; require(_new <= reservePriceMax, "update:reserve price too high"); votingTokens += weight; reserveTotal += weight * _new; } // they no longer want to vote else if (_new == 0) { votingTokens -= weight; reserveTotal -= weight * old; } // they are updating their vote else { uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight); uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; require(_new >= reservePriceMin, "update:reserve price too low"); uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; require(_new <= reservePriceMax, "update:reserve price too high"); reserveTotal = reserveTotal + (weight * _new) - (weight * old); } userPrices[msg.sender] = _new; emit PriceUpdate(msg.sender, _new); } /// @notice an internal function used to update sender and receivers price on token transfer /// @param _from the ERC20 token sender /// @param _to the ERC20 token receiver /// @param _amount the ERC20 token amount function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override { if (_from != address(0) && auctionState == State.inactive) { uint256 fromPrice = userPrices[_from]; uint256 toPrice = userPrices[_to]; // only do something if users have different reserve price if (toPrice != fromPrice) { // new holder is not a voter if (toPrice == 0) { // get the average reserve price ignoring the senders amount votingTokens -= _amount; reserveTotal -= _amount * fromPrice; } // old holder is not a voter else if (fromPrice == 0) { votingTokens += _amount; reserveTotal += _amount * toPrice; } // both holders are voters else { reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice); } } } } /// @notice kick off an auction. Must send reservePrice in ETH function start() external payable { require(auctionState == State.inactive, "start:no auction starts"); require(msg.value >= reservePrice(), "start:too low bid"); require(votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply(), "start:not enough voters"); auctionEnd = block.timestamp + auctionLength; auctionState = State.live; livePrice = msg.value; winning = payable(msg.sender); emit Start(msg.sender, msg.value); } /// @notice an external function to bid on purchasing the vaults NFT. The msg.value is the bid amount function bid() external payable { require(auctionState == State.live, "bid:auction is not live"); uint256 increase = ISettings(settings).minBidIncrease() + 1000; require(msg.value * 1000 >= livePrice * increase, "bid:too low bid"); require(block.timestamp < auctionEnd, "bid:auction ended"); // If bid is within 15 minutes of auction end, extend auction if (auctionEnd - block.timestamp <= 15 minutes) { auctionEnd += 15 minutes; } _sendWETH(winning, livePrice); livePrice = msg.value; winning = payable(msg.sender); emit Bid(msg.sender, msg.value); } /// @notice an external function to end an auction after the timer has run out function end() external { require(auctionState == State.live, "end:vault has already closed"); require(block.timestamp >= auctionEnd, "end:auction live"); _claimFees(); // transfer erc721 to winner IERC721(token).transferFrom(address(this), winning, id); auctionState = State.ended; emit Won(winning, livePrice); } /// @notice an external function to burn all ERC20 tokens to receive the ERC721 token function redeem() external { require(auctionState == State.inactive, "redeem:no redeeming"); _burn(msg.sender, totalSupply()); // transfer erc721 to redeemer IERC721(token).transferFrom(address(this), msg.sender, id); auctionState = State.redeemed; emit Redeem(msg.sender); } /// @notice an external function to burn ERC20 tokens to receive ETH from ERC721 token purchase function cash() external { require(auctionState == State.ended, "cash:vault not closed yet"); uint256 bal = balanceOf(msg.sender); require(bal > 0, "cash:no tokens to cash out"); uint256 share = bal * address(this).balance / totalSupply(); _burn(msg.sender, bal); _sendETHOrWETH(payable(msg.sender), share); emit Cash(msg.sender, share); } /// @dev internal helper function to send ETH and WETH on failure function _sendWETH(address who, uint256 amount) internal { IWETH(weth).deposit{value: amount}(); IWETH(weth).transfer(who, IWETH(weth).balanceOf(address(this))); } /// @dev internal helper function to send ETH and WETH on failure function _sendETHOrWETH(address who, uint256 amount) internal { // contracts get bet WETH because they can be mean if (who.isContract()) { IWETH(weth).deposit{value: amount}(); IWETH(weth).transfer(who, IWETH(weth).balanceOf(address(this))); } else { payable(who).transfer(amount); } } } // 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 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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.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; 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; /** * @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 "./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 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(type(IERC165).interfaceId); } /** * @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.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.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.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; interface ISettings { function maxAuctionLength() external returns(uint256); function minAuctionLength() external returns(uint256); function maxCuratorFee() external returns(uint256); function governanceFee() external returns(uint256); function minBidIncrease() external returns(uint256); function minVotePercentage() external returns(uint256); function maxReserveFactor() external returns(uint256); function minReserveFactor() external returns(uint256); function feeReceiver() external returns(address payable); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns(bool); function transfer(address, uint) external returns(bool); function transferFrom(address, address, uint) external returns(bool); function balanceOf(address) external view returns(uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three 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 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 this function is * overloaded; * * 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 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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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 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.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); }
the function to mint a new vault _name the desired name of the vault _symbol the desired sumbol of the vault _token the ERC721 token address fo the NFT _id the uint256 ID of the token _listPrice the initial price of the NFT return the ID of the vault
function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external whenNotPaused returns(uint256) { TokenVault vault = new TokenVault(settings, msg.sender, _token, _id, _supply, _listPrice, _fee, _name, _symbol); emit Mint(_token, _id, _listPrice, address(vault), vaultCount); IERC721(_token).safeTransferFrom(msg.sender, address(vault), _id); vaults[vaultCount] = vault; vaultCount++; return vaultCount - 1; }
11,686,977
./full_match/1/0x42E1bA48137cf3f91A84d8C81AEeBbCaeA44F40f/sources/ZooToken.sol
Gets the current votes balance for `account` account The address to get votes balance return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
16,462,673
pragma solidity ^0.5.2; contract IERC223 { /* IERC20 */ function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function allowance(address owner, address spender) public view returns (uint256); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed _from, address indexed _to, uint256 _value); /* IERC223 */ function transfer(address to, uint256 value) public returns (bool); function transfer(address to, uint256 value, bytes memory data) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes memory _data) public; } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title SafeERC223 * @dev Wrappers around ERC223 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 SafeERC223 for ERC223;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC223 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC223 token, address to, uint256 value) internal { // callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); require(token.transfer(to, value)); } function safeTransfer(IERC223 token, address to, uint256 value, bytes memory data) internal { // callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value, data)); require(token.transfer(to, value, data)); } function safeTransferFrom(IERC223 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC223 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), "SafeERC223: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC223 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(IERC223 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(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(IERC223 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(), "SafeERC223: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC223: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC223: ERC223 operation did not succeed"); } } } /** * @dev A token holder contract that will allow a beneficiary to extract the * tokens after a given release time. */ contract TokenTimelock is ERC223ReceivingContract { using SafeERC223 for IERC223; // ERC20 basic token contract being held IERC223 private _token; // beneficiary of tokens after they are released address private _beneficiary; // timestamp when token release is enabled uint256 private _releaseTime; constructor (IERC223 token, address beneficiary, uint256 releaseTime) public { // solhint-disable-next-line not-rely-on-time require(releaseTime > block.timestamp, "TokenTimelock: release time is before current time"); _token = token; _beneficiary = beneficiary; _releaseTime = releaseTime; } /** * @return the token being held. */ function token() public view returns (IERC223) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solhint-disable-next-line not-rely-on-time require(block.timestamp >= _releaseTime, "TokenTimelock: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TokenTimelock: no tokens to release"); _token.safeTransfer(_beneficiary, amount); } /** * Empty implementation */ function tokenFallback(address /*_from*/, uint /*_value*/, bytes memory /*_data*/) public { return; } }
return the token being held./
function token() public view returns (IERC223) { return _token; }
983,774
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[emailย protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[emailย protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[emailย protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[emailย protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[emailย protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[emailย protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/dispatcher/IMigrationHookHandler.sol"; import "../../extensions/IExtension.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../infrastructure/protocol-fees/IProtocolFeeTracker.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[emailย protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler, GasRelayRecipientMixin { event BuySharesOnBehalfCallerDeregistered(address caller); event BuySharesOnBehalfCallerRegistered(address caller); event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock ); event GasLimitsForDestructCallSet( uint256 nextDeactivateFeeManagerGasLimit, uint256 nextPayProtocolFeeGasLimit ); event MigrationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy ); event NewFundCreated(address indexed creator, address vaultProxy, address comptrollerProxy); event ProtocolFeeTrackerSet(address protocolFeeTracker); event ReconfigurationRequestCancelled( address indexed vaultProxy, address indexed nextComptrollerProxy ); event ReconfigurationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy, uint256 executableTimestamp ); event ReconfigurationRequestExecuted( address indexed vaultProxy, address indexed prevComptrollerProxy, address indexed nextComptrollerProxy ); event ReconfigurationTimelockSet(uint256 nextTimelock); event ReleaseIsLive(); event VaultCallDeregistered( address indexed contractAddress, bytes4 selector, bytes32 dataHash ); event VaultCallRegistered(address indexed contractAddress, bytes4 selector, bytes32 dataHash); event VaultLibSet(address vaultLib); struct ReconfigurationRequest { address nextComptrollerProxy; uint256 executableTimestamp; } // Constants // keccak256(abi.encodePacked("mln.vaultCall.any") bytes32 private constant ANY_VAULT_CALL = 0x5bf1898dd28c4d29f33c4c1bb9b8a7e2f6322847d70be63e8f89de024d08a669; address private immutable CREATOR; address private immutable DISPATCHER; // Pseudo-constants (can only be set once) address private comptrollerLib; address private protocolFeeTracker; address private vaultLib; // Storage uint32 private gasLimitForDestructCallToDeactivateFeeManager; // Can reduce to uint16 uint32 private gasLimitForDestructCallToPayProtocolFee; // Can reduce to uint16 bool private isLive; uint256 private reconfigurationTimelock; mapping(address => bool) private acctToIsAllowedBuySharesOnBehalfCaller; mapping(bytes32 => mapping(bytes32 => bool)) private vaultCallToPayloadToIsAllowed; mapping(address => ReconfigurationRequest) private vaultProxyToReconfigurationRequest; modifier onlyDispatcher() { require(msg.sender == DISPATCHER, "Only Dispatcher can call this function"); _; } modifier onlyLiveRelease() { require(releaseIsLive(), "Release is not yet live"); _; } modifier onlyMigrator(address _vaultProxy) { __assertIsMigrator(_vaultProxy, __msgSender()); _; } modifier onlyMigratorNotRelayable(address _vaultProxy) { __assertIsMigrator(_vaultProxy, msg.sender); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier pseudoConstant(address _storageValue) { require(_storageValue == address(0), "This value can only be set once"); _; } function __assertIsMigrator(address _vaultProxy, address _who) private view { require( IVault(_vaultProxy).canMigrate(_who), "Only a permissioned migrator can call this function" ); } constructor(address _dispatcher, address _gasRelayPaymasterFactory) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { // Validate constants require( ANY_VAULT_CALL == keccak256(abi.encodePacked("mln.vaultCall.any")), "constructor: Incorrect ANY_VAULT_CALL" ); CREATOR = msg.sender; DISPATCHER = _dispatcher; // Estimated base call cost: 17k // Per fee that uses shares outstanding (default recipient): 33k // 300k accommodates up to 8 such fees gasLimitForDestructCallToDeactivateFeeManager = 300000; // Estimated cost: 50k gasLimitForDestructCallToPayProtocolFee = 200000; reconfigurationTimelock = 2 days; } ////////////////////////////////////// // PSEUDO-CONSTANTS (only set once) // ////////////////////////////////////// /// @notice Sets the ComptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address function setComptrollerLib(address _comptrollerLib) external onlyOwner pseudoConstant(getComptrollerLib()) { comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the ProtocolFeeTracker /// @param _protocolFeeTracker The ProtocolFeeTracker contract address function setProtocolFeeTracker(address _protocolFeeTracker) external onlyOwner pseudoConstant(getProtocolFeeTracker()) { protocolFeeTracker = _protocolFeeTracker; emit ProtocolFeeTrackerSet(_protocolFeeTracker); } /// @notice Sets the VaultLib /// @param _vaultLib The VaultLib contract address function setVaultLib(address _vaultLib) external onlyOwner pseudoConstant(getVaultLib()) { vaultLib = _vaultLib; emit VaultLibSet(_vaultLib); } ///////////// // GENERAL // ///////////// /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev The owner is initially the contract's creator, for convenience in setting up configuration. /// Ownership is handed-off when the creator calls setReleaseLive(). function getOwner() public view override returns (address owner_) { if (!releaseIsLive()) { return getCreator(); } return IDispatcher(getDispatcher()).getOwner(); } /// @notice Sets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @param _nextDeactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _nextPayProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee function setGasLimitsForDestructCall( uint32 _nextDeactivateFeeManagerGasLimit, uint32 _nextPayProtocolFeeGasLimit ) external onlyOwner { require( _nextDeactivateFeeManagerGasLimit > 0 && _nextPayProtocolFeeGasLimit > 0, "setGasLimitsForDestructCall: Zero value not allowed" ); gasLimitForDestructCallToDeactivateFeeManager = _nextDeactivateFeeManagerGasLimit; gasLimitForDestructCallToPayProtocolFee = _nextPayProtocolFeeGasLimit; emit GasLimitsForDestructCallSet( _nextDeactivateFeeManagerGasLimit, _nextPayProtocolFeeGasLimit ); } /// @notice Sets the release as live /// @dev A live release allows funds to be created and migrated once this contract /// is set as the Dispatcher.currentFundDeployer function setReleaseLive() external { require( msg.sender == getCreator(), "setReleaseLive: Only the creator can call this function" ); require(!releaseIsLive(), "setReleaseLive: Already live"); // All pseudo-constants should be set require(getComptrollerLib() != address(0), "setReleaseLive: comptrollerLib is not set"); require( getProtocolFeeTracker() != address(0), "setReleaseLive: protocolFeeTracker is not set" ); require(getVaultLib() != address(0), "setReleaseLive: vaultLib is not set"); isLive = true; emit ReleaseIsLive(); } /// @dev Helper to call ComptrollerProxy.destructActivated() with the correct params function __destructActivatedComptrollerProxy(address _comptrollerProxy) private { ( uint256 deactivateFeeManagerGasLimit, uint256 payProtocolFeeGasLimit ) = getGasLimitsForDestructCall(); IComptroller(_comptrollerProxy).destructActivated( deactivateFeeManagerGasLimit, payProtocolFeeGasLimit ); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the migration process /// @param _vaultProxy The VaultProxy to migrate /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while signaling migration /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigrationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData, bool _bypassPrevReleaseFailure ) external onlyLiveRelease onlyMigratorNotRelayable(_vaultProxy) returns (address comptrollerProxy_) { // Bad _vaultProxy value is validated by Dispatcher.signalMigration() require( !IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy), "createMigrationRequest: A MigrationRequest already exists" ); comptrollerProxy_ = __deployComptrollerProxy( msg.sender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); IDispatcher(getDispatcher()).signalMigration( _vaultProxy, comptrollerProxy_, getVaultLib(), _bypassPrevReleaseFailure ); emit MigrationRequestCreated(msg.sender, _vaultProxy, comptrollerProxy_); return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund's shares token /// @param _fundSymbol The symbol of the fund's shares token /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, string calldata _fundSymbol, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { // _fundOwner is validated by VaultLib.__setOwner() address canonicalSender = __msgSender(); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); vaultProxy_ = __deployVaultProxy(_fundOwner, comptrollerProxy_, _fundName, _fundSymbol); IComptroller comptrollerContract = IComptroller(comptrollerProxy_); comptrollerContract.setVaultProxy(vaultProxy_); __configureExtensions( comptrollerProxy_, vaultProxy_, _feeManagerConfigData, _policyManagerConfigData ); comptrollerContract.activate(false); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(vaultProxy_); emit NewFundCreated(canonicalSender, vaultProxy_, comptrollerProxy_); return (comptrollerProxy_, vaultProxy_); } /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the reconfiguration process /// @param _vaultProxy The VaultProxy to reconfigure /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createReconfigurationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external returns (address comptrollerProxy_) { address canonicalSender = __msgSender(); __assertIsMigrator(_vaultProxy, canonicalSender); require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "createReconfigurationRequest: VaultProxy not on this release" ); require( !hasReconfigurationRequest(_vaultProxy), "createReconfigurationRequest: VaultProxy has a pending reconfiguration request" ); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); uint256 executableTimestamp = block.timestamp + getReconfigurationTimelock(); vaultProxyToReconfigurationRequest[_vaultProxy] = ReconfigurationRequest({ nextComptrollerProxy: comptrollerProxy_, executableTimestamp: executableTimestamp }); emit ReconfigurationRequestCreated( canonicalSender, _vaultProxy, comptrollerProxy_, executableTimestamp ); return comptrollerProxy_; } /// @dev Helper function to configure the Extensions for a given ComptrollerProxy function __configureExtensions( address _comptrollerProxy, address _vaultProxy, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private { // Since fees can only be set in this step, if there are no fees, there is no need to set the validated VaultProxy if (_feeManagerConfigData.length > 0) { IExtension(IComptroller(_comptrollerProxy).getFeeManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _feeManagerConfigData ); } // For all other extensions, we call to cache the validated VaultProxy, for simplicity. // In the future, we can consider caching conditionally. IExtension(IComptroller(_comptrollerProxy).getExternalPositionManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getIntegrationManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getPolicyManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _policyManagerConfigData ); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _canonicalSender, address _denominationAsset, uint256 _sharesActionTimelock ) private returns (address comptrollerProxy_) { // _denominationAsset is validated by ComptrollerLib.init() bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, getComptrollerLib())); emit ComptrollerProxyDeployed( _canonicalSender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock ); return comptrollerProxy_; } /// @dev Helper to deploy a new VaultProxy instance during fund creation. /// Avoids stack-too-deep error. function __deployVaultProxy( address _fundOwner, address _comptrollerProxy, string calldata _fundName, string calldata _fundSymbol ) private returns (address vaultProxy_) { vaultProxy_ = IDispatcher(getDispatcher()).deployVaultProxy( getVaultLib(), _fundOwner, _comptrollerProxy, _fundName ); if (bytes(_fundSymbol).length != 0) { IVault(vaultProxy_).setSymbol(_fundSymbol); } return vaultProxy_; } /////////////////////////////////////////////// // RECONFIGURATION (INTRA-RELEASE MIGRATION) // /////////////////////////////////////////////// /// @notice Cancels a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to cancel the reconfiguration request function cancelReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { address nextComptrollerProxy = vaultProxyToReconfigurationRequest[_vaultProxy] .nextComptrollerProxy; require( nextComptrollerProxy != address(0), "cancelReconfiguration: No reconfiguration request exists for _vaultProxy" ); // Destroy the nextComptrollerProxy IComptroller(nextComptrollerProxy).destructUnactivated(); // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestCancelled(_vaultProxy, nextComptrollerProxy); } /// @notice Executes a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to execute the reconfiguration request /// @dev ProtocolFeeTracker.initializeForVault() does not need to be included in a reconfiguration, /// as it refers to the vault and not the new ComptrollerProxy function executeReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { ReconfigurationRequest memory request = getReconfigurationRequestForVaultProxy( _vaultProxy ); require( request.nextComptrollerProxy != address(0), "executeReconfiguration: No reconfiguration request exists for _vaultProxy" ); require( block.timestamp >= request.executableTimestamp, "executeReconfiguration: The reconfiguration timelock has not elapsed" ); // Not technically necessary, but a nice assurance require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "executeReconfiguration: _vaultProxy is no longer on this release" ); // Unwind and destroy the prevComptrollerProxy before setting the nextComptrollerProxy as the VaultProxy.accessor address prevComptrollerProxy = IVault(_vaultProxy).getAccessor(); address paymaster = IComptroller(prevComptrollerProxy).getGasRelayPaymaster(); __destructActivatedComptrollerProxy(prevComptrollerProxy); // Execute the reconfiguration IVault(_vaultProxy).setAccessorForFundReconfiguration(request.nextComptrollerProxy); // Activate the new ComptrollerProxy IComptroller(request.nextComptrollerProxy).activate(true); if (paymaster != address(0)) { IComptroller(request.nextComptrollerProxy).setGasRelayPaymaster(paymaster); } // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestExecuted( _vaultProxy, prevComptrollerProxy, request.nextComptrollerProxy ); } /// @notice Sets a new reconfiguration timelock /// @param _nextTimelock The number of seconds for the new timelock function setReconfigurationTimelock(uint256 _nextTimelock) external onlyOwner { reconfigurationTimelock = _nextTimelock; emit ReconfigurationTimelockSet(_nextTimelock); } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while canceling migration function cancelMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher(getDispatcher()).cancelMigration(_vaultProxy, _bypassPrevReleaseFailure); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while executing migration function executeMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(getDispatcher()); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassPrevReleaseFailure); IComptroller(comptrollerProxy).activate(true); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(_vaultProxy); } /// @notice Executes logic when a migration is canceled on the Dispatcher /// @param _nextComptrollerProxy The ComptrollerProxy created on this release function invokeMigrationInCancelHook( address, address, address _nextComptrollerProxy, address ) external override onlyDispatcher { IComptroller(_nextComptrollerProxy).destructUnactivated(); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override onlyDispatcher { if (_hook != MigrationOutHook.PreMigrate) { return; } // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config __destructActivatedComptrollerProxy(comptrollerProxy); } ////////////// // REGISTRY // ////////////// // BUY SHARES CALLERS /// @notice Deregisters allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The callers to deregister function deregisterBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( isAllowedBuySharesOnBehalfCaller(_callers[i]), "deregisterBuySharesOnBehalfCallers: Caller not registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = false; emit BuySharesOnBehalfCallerDeregistered(_callers[i]); } } /// @notice Registers allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The allowed callers /// @dev Validate that each registered caller only forwards requests to buy shares that /// originate from the same _buyer passed into buySharesOnBehalf(). This is critical /// to the integrity of VaultProxy.freelyTransferableShares. function registerBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( !isAllowedBuySharesOnBehalfCaller(_callers[i]), "registerBuySharesOnBehalfCallers: Caller already registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = true; emit BuySharesOnBehalfCallerRegistered(_callers[i]); } } // VAULT CALLS /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register /// @param _dataHashes The keccak call data hashes of the calls to de-register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function deregisterVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "deregisterVaultCalls: Call not registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register /// @param _dataHashes The keccak call data hashes of the calls to register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function registerVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "registerVaultCalls: Call already registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Checks if a contract call is allowed /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isAllowed_ True if the call is allowed /// @dev A vault call is allowed if the _dataHash is specifically allowed, /// or if any _dataHash is allowed function isAllowedVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) external view override returns (bool isAllowed_) { bytes32 contractFunctionHash = keccak256(abi.encodePacked(_contract, _selector)); return vaultCallToPayloadToIsAllowed[contractFunctionHash][_dataHash] || vaultCallToPayloadToIsAllowed[contractFunctionHash][ANY_VAULT_CALL]; } // PUBLIC FUNCTIONS /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() public view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() public view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @return deactivateFeeManagerGasLimit_ The amount of gas to forward to deactivate the FeeManager /// @return payProtocolFeeGasLimit_ The amount of gas to forward to pay the protocol fee function getGasLimitsForDestructCall() public view returns (uint256 deactivateFeeManagerGasLimit_, uint256 payProtocolFeeGasLimit_) { return ( gasLimitForDestructCallToDeactivateFeeManager, gasLimitForDestructCallToPayProtocolFee ); } /// @notice Gets the `protocolFeeTracker` variable value /// @return protocolFeeTracker_ The `protocolFeeTracker` variable value function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) { return protocolFeeTracker; } /// @notice Gets the pending ReconfigurationRequest for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return reconfigurationRequest_ The pending ReconfigurationRequest function getReconfigurationRequestForVaultProxy(address _vaultProxy) public view returns (ReconfigurationRequest memory reconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy]; } /// @notice Gets the amount of time that must pass before executing a ReconfigurationRequest /// @return reconfigurationTimelock_ The timelock value (in seconds) function getReconfigurationTimelock() public view returns (uint256 reconfigurationTimelock_) { return reconfigurationTimelock; } /// @notice Gets the `vaultLib` variable value /// @return vaultLib_ The `vaultLib` variable value function getVaultLib() public view returns (address vaultLib_) { return vaultLib; } /// @notice Checks whether a ReconfigurationRequest exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasReconfigurationRequest_ True if a ReconfigurationRequest exists function hasReconfigurationRequest(address _vaultProxy) public view override returns (bool hasReconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy].nextComptrollerProxy != address(0); } /// @notice Checks if an account is an allowed caller of ComptrollerProxy.buySharesOnBehalf() /// @param _who The account to check /// @return isAllowed_ True if the account is an allowed caller function isAllowedBuySharesOnBehalfCaller(address _who) public view override returns (bool isAllowed_) { return acctToIsAllowedBuySharesOnBehalfCaller[_who]; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) public view returns (bool isRegistered_) { return vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contract, _selector) )][_dataHash]; } /// @notice Gets the `isLive` variable value /// @return isLive_ The `isLive` variable value function releaseIsLive() public view returns (bool isLive_) { return isLive; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[emailย protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[emailย protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/NonUpgradableProxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[emailย protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is NonUpgradableProxy { constructor(bytes memory _constructData, address _comptrollerLib) public NonUpgradableProxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[emailย protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[emailย protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[emailย protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[emailย protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[emailย protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[emailย protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[emailย protected]> /// @notice Manages policies for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official policies only. /// Policies that restrict current investors can only be added upon fund setup, migration, or reconfiguration. /// Policies that restrict new investors or asset management actions can be added at any time. /// Policies themselves specify whether or not they are allowed to be updated or removed. contract PolicyManager is IPolicyManager, ExtensionBase, GasRelayRecipientMixin { using AddressArrayLib for address[]; event PolicyDisabledOnHookForFund( address indexed comptrollerProxy, address indexed policy, PolicyHook indexed hook ); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); uint256 private constant POLICY_HOOK_COUNT = 10; mapping(address => mapping(PolicyHook => address[])) private comptrollerProxyToHookToPolicies; modifier onlyFundOwner(address _comptrollerProxy) { require( __msgSender() == IVault(getVaultProxyForFund(_comptrollerProxy)).getOwner(), "Only the fund owner can call this function" ); _; } constructor(address _fundDeployer, address _gasRelayPaymasterFactory) public ExtensionBase(_fundDeployer) GasRelayRecipientMixin(_gasRelayPaymasterFactory) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev There will be no enabledPolicies if the caller is not a valid ComptrollerProxy function activateForFund(bool _isMigratedFund) external override { address comptrollerProxy = msg.sender; // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(comptrollerProxy); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(comptrollerProxy, enabledPolicies[i]); } } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable /// @dev If an arbitrary policy changes its `implementedHooks()` return values after it is /// already enabled on a fund, then this will not correctly disable the policy from any /// removed hook values. function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyFundOwner(_comptrollerProxy) { require(IPolicy(_policy).canDisable(), "disablePolicyForFund: _policy cannot be disabled"); PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { bool disabled = comptrollerProxyToHookToPolicies[_comptrollerProxy][implementedHooks[i]] .removeStorageItem(_policy); if (disabled) { emit PolicyDisabledOnHookForFund(_comptrollerProxy, _policy, implementedHooks[i]); } } } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { require( !__policyHookRestrictsCurrentInvestorActions(implementedHooks[i]), "enablePolicyForFund: _policy restricts actions of current investors" ); } __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData, implementedHooks); __activatePolicyForFund(_comptrollerProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); // In case there are no policies yet if (_configData.length == 0) { return; } (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund( _comptrollerProxy, policies[i], settingsData[i], IPolicy(policies[i]).implementedHooks() ); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { IPolicy(_policy).updateFundSettings(_comptrollerProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { // Return as quickly as possible if no policies to run address[] memory policies = getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook); if (policies.length == 0) { return; } // Limit calls to trusted components, in case policies update local storage upon runs require( msg.sender == _comptrollerProxy || msg.sender == IComptroller(_comptrollerProxy).getIntegrationManager() || msg.sender == IComptroller(_comptrollerProxy).getExternalPositionManager(), "validatePolicies: Caller not allowed" ); for (uint256 i; i < policies.length; i++) { require( IPolicy(policies[i]).validateRule(_comptrollerProxy, _hook, _validationData), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund(address _comptrollerProxy, address _policy) private { IPolicy(_policy).activateForFund(_comptrollerProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData, PolicyHook[] memory _hooks ) private { // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy for (uint256 i; i < _hooks.length; i++) { require( !policyIsEnabledOnHookForFund(_comptrollerProxy, _hooks[i], _policy), "__enablePolicyForFund: Policy is already enabled" ); comptrollerProxyToHookToPolicies[_comptrollerProxy][_hooks[i]].push(_policy); } emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to get all the hooks available to policies function __getAllPolicyHooks() private pure returns (PolicyHook[POLICY_HOOK_COUNT] memory hooks_) { return [ PolicyHook.PostBuyShares, PolicyHook.PostCallOnIntegration, PolicyHook.PreTransferShares, PolicyHook.RedeemSharesForSpecificAssets, PolicyHook.AddTrackedAssets, PolicyHook.RemoveTrackedAssets, PolicyHook.CreateExternalPosition, PolicyHook.PostCallOnExternalPosition, PolicyHook.RemoveExternalPosition, PolicyHook.ReactivateExternalPosition ]; } /// @dev Helper to check if a policy hook restricts the actions of current investors. /// These hooks should not allow policy additions post-deployment or post-migration. function __policyHookRestrictsCurrentInvestorActions(PolicyHook _hook) private pure returns (bool restrictsActions_) { return _hook == PolicyHook.PreTransferShares || _hook == PolicyHook.RedeemSharesForSpecificAssets; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled policies for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { PolicyHook[POLICY_HOOK_COUNT] memory hooks = __getAllPolicyHooks(); for (uint256 i; i < hooks.length; i++) { enabledPolicies_ = enabledPolicies_.mergeArray( getEnabledPoliciesOnHookForFund(_comptrollerProxy, hooks[i]) ); } return enabledPolicies_; } /// @notice Get a list of enabled policies that run on a given hook for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesOnHookForFund(address _comptrollerProxy, PolicyHook _hook) public view returns (address[] memory enabledPolicies_) { return comptrollerProxyToHookToPolicies[_comptrollerProxy][_hook]; } /// @notice Check whether a given policy runs on a given hook for a given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @param _policy The policy /// @return isEnabled_ True if the policy is enabled function policyIsEnabledOnHookForFund( address _comptrollerProxy, PolicyHook _hook, address _policy ) public view returns (bool isEnabled_) { return getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook).contains(_policy); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]e.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[emailย protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../interfaces/IGsnRelayHub.sol"; import "../../interfaces/IGsnTypes.sol"; import "../../interfaces/IWETH.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/IVault.sol"; import "../../core/fund-deployer/FundDeployer.sol"; import "../../extensions/policy-manager/PolicyManager.sol"; import "./bases/GasRelayPaymasterLibBase1.sol"; import "./IGasRelayPaymaster.sol"; import "./IGasRelayPaymasterDepositor.sol"; /// @title GasRelayPaymasterLib Contract /// @author Enzyme Council <[emailย protected]> /// @notice The core logic library for the "paymaster" contract which refunds GSN relayers contract GasRelayPaymasterLib is IGasRelayPaymaster, GasRelayPaymasterLibBase1 { using SafeMath for uint256; // Immutable and constants // Sane defaults, subject to change after gas profiling uint256 private constant CALLDATA_SIZE_LIMIT = 10500; // Deposit in wei uint256 private constant DEPOSIT = 0.2 ether; // Sane defaults, subject to change after gas profiling uint256 private constant PRE_RELAYED_CALL_GAS_LIMIT = 100000; uint256 private constant POST_RELAYED_CALL_GAS_LIMIT = 110000; // FORWARDER_HUB_OVERHEAD = 50000; // PAYMASTER_ACCEPTANCE_BUDGET = FORWARDER_HUB_OVERHEAD + PRE_RELAYED_CALL_GAS_LIMIT uint256 private constant PAYMASTER_ACCEPTANCE_BUDGET = 150000; address private immutable RELAY_HUB; address private immutable TRUSTED_FORWARDER; address private immutable WETH_TOKEN; modifier onlyComptroller() { require( msg.sender == getParentComptroller(), "Can only be called by the parent comptroller" ); _; } modifier relayHubOnly() { require(msg.sender == getHubAddr(), "Can only be called by RelayHub"); _; } constructor( address _wethToken, address _relayHub, address _trustedForwarder ) public { RELAY_HUB = _relayHub; TRUSTED_FORWARDER = _trustedForwarder; WETH_TOKEN = _wethToken; } // INIT /// @notice Initializes a paymaster proxy /// @param _vault The VaultProxy associated with the paymaster proxy /// @dev Used to set the owning vault function init(address _vault) external { require(getParentVault() == address(0), "init: Paymaster already initialized"); parentVault = _vault; } // EXTERNAL FUNCTIONS /// @notice Pull deposit from the vault and reactivate relaying function deposit() external override onlyComptroller { __depositMax(); } /// @notice Checks whether the paymaster will pay for a given relayed tx /// @param _relayRequest The full relay request structure /// @return context_ The tx signer and the fn sig, encoded so that it can be passed to `postRelayCall` /// @return rejectOnRecipientRevert_ Always false function preRelayedCall( IGsnTypes.RelayRequest calldata _relayRequest, bytes calldata, bytes calldata, uint256 ) external override relayHubOnly returns (bytes memory context_, bool rejectOnRecipientRevert_) { address vaultProxy = getParentVault(); require( IVault(vaultProxy).canRelayCalls(_relayRequest.request.from), "preRelayedCall: Unauthorized caller" ); bytes4 selector = __parseTxDataFunctionSelector(_relayRequest.request.data); require( __isAllowedCall( vaultProxy, _relayRequest.request.to, selector, _relayRequest.request.data ), "preRelayedCall: Function call not permitted" ); return (abi.encode(_relayRequest.request.from, selector), false); } /// @notice Called by the relay hub after the relayed tx is executed, tops up deposit if flag passed through paymasterdata is true /// @param _context The context constructed by preRelayedCall (used to pass data from pre to post relayed call) /// @param _success Whether or not the relayed tx succeed /// @param _relayData The relay params of the request. can be used by relayHub.calculateCharge() function postRelayedCall( bytes calldata _context, bool _success, uint256, IGsnTypes.RelayData calldata _relayData ) external override relayHubOnly { bool shouldTopUpDeposit = abi.decode(_relayData.paymasterData, (bool)); if (shouldTopUpDeposit) { __depositMax(); } (address spender, bytes4 selector) = abi.decode(_context, (address, bytes4)); emit TransactionRelayed(spender, selector, _success); } /// @notice Send any deposited ETH back to the vault function withdrawBalance() external override { address vaultProxy = getParentVault(); require( msg.sender == IVault(vaultProxy).getOwner() || msg.sender == __getComptrollerForVault(vaultProxy), "withdrawBalance: Only owner or comptroller is authorized" ); IGsnRelayHub(getHubAddr()).withdraw(getRelayHubDeposit(), payable(address(this))); uint256 amount = address(this).balance; Address.sendValue(payable(vaultProxy), amount); emit Withdrawn(amount); } // PUBLIC FUNCTIONS /// @notice Gets the current ComptrollerProxy of the VaultProxy associated with this contract /// @return parentComptroller_ The ComptrollerProxy function getParentComptroller() public view returns (address parentComptroller_) { return __getComptrollerForVault(parentVault); } // PRIVATE FUNCTIONS /// @dev Helper to pull WETH from the associated vault to top up to the max ETH deposit in the relay hub function __depositMax() private { uint256 prevDeposit = getRelayHubDeposit(); if (prevDeposit < DEPOSIT) { uint256 amount = DEPOSIT.sub(prevDeposit); IGasRelayPaymasterDepositor(getParentComptroller()).pullWethForGasRelayer(amount); IWETH(getWethToken()).withdraw(amount); IGsnRelayHub(getHubAddr()).depositFor{value: amount}(address(this)); emit Deposited(amount); } } /// @dev Helper to get the ComptrollerProxy for a given VaultProxy function __getComptrollerForVault(address _vaultProxy) private view returns (address comptrollerProxy_) { return IVault(_vaultProxy).getAccessor(); } /// @dev Helper to check if a contract call is allowed to be relayed using this paymaster /// Allowed contracts are: /// - VaultProxy /// - ComptrollerProxy /// - PolicyManager /// - FundDeployer function __isAllowedCall( address _vaultProxy, address _contract, bytes4 _selector, bytes calldata _txData ) private view returns (bool allowed_) { if (_contract == _vaultProxy) { // All calls to the VaultProxy are allowed return true; } address parentComptroller = __getComptrollerForVault(_vaultProxy); if (_contract == parentComptroller) { if ( _selector == ComptrollerLib.callOnExtension.selector || _selector == ComptrollerLib.vaultCallOnContract.selector || _selector == ComptrollerLib.buyBackProtocolFeeShares.selector || _selector == ComptrollerLib.depositToGasRelayPaymaster.selector || _selector == ComptrollerLib.setAutoProtocolFeeSharesBuyback.selector ) { return true; } } else if (_contract == ComptrollerLib(parentComptroller).getPolicyManager()) { if ( _selector == PolicyManager.updatePolicySettingsForFund.selector || _selector == PolicyManager.enablePolicyForFund.selector || _selector == PolicyManager.disablePolicyForFund.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentComptroller(); } } else if (_contract == ComptrollerLib(parentComptroller).getFundDeployer()) { if ( _selector == FundDeployer.createReconfigurationRequest.selector || _selector == FundDeployer.executeReconfiguration.selector || _selector == FundDeployer.cancelReconfiguration.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentVault(); } } return false; } /// @notice Parses the first parameter of tx data as an address /// @param _txData The tx data to retrieve the address from /// @return retrievedAddress_ The extracted address function __parseTxDataFirstParameterAsAddress(bytes calldata _txData) private pure returns (address retrievedAddress_) { require( _txData.length >= 36, "__parseTxDataFirstParameterAsAddress: _txData is not a valid length" ); return abi.decode(_txData[4:36], (address)); } /// @notice Parses the function selector from tx data /// @param _txData The tx data /// @return functionSelector_ The extracted function selector function __parseTxDataFunctionSelector(bytes calldata _txData) private pure returns (bytes4 functionSelector_) { /// convert bytes[:4] to bytes4 require( _txData.length >= 4, "__parseTxDataFunctionSelector: _txData is not a valid length" ); functionSelector_ = _txData[0] | (bytes4(_txData[1]) >> 8) | (bytes4(_txData[2]) >> 16) | (bytes4(_txData[3]) >> 24); return functionSelector_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets gas limits used by the relay hub for the pre and post relay calls /// @return limits_ `GasAndDataLimits(PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT)` function getGasAndDataLimits() external view override returns (IGsnPaymaster.GasAndDataLimits memory limits_) { return IGsnPaymaster.GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } /// @notice Gets the `RELAY_HUB` variable value /// @return relayHub_ The `RELAY_HUB` value function getHubAddr() public view override returns (address relayHub_) { return RELAY_HUB; } /// @notice Gets the `parentVault` variable value /// @return parentVault_ The `parentVault` value function getParentVault() public view returns (address parentVault_) { return parentVault; } /// @notice Look up amount of ETH deposited on the relay hub /// @return depositBalance_ amount of ETH deposited on the relay hub function getRelayHubDeposit() public view override returns (uint256 depositBalance_) { return IGsnRelayHub(getHubAddr()).balanceOf(address(this)); } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the `TRUSTED_FORWARDER` variable value /// @return trustedForwarder_ The forwarder contract which is trusted to validated the relayed tx signature function trustedForwarder() external view override returns (address trustedForwarder_) { return TRUSTED_FORWARDER; } /// @notice Gets the string representation of the contract version (fulfills interface) /// @return versionString_ The version string function versionPaymaster() external view override returns (string memory versionString_) { return "2.2.3+opengsn.enzymefund.ipaymaster"; } } // 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. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[emailย protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[emailย protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[emailย protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title GasRelayPaymasterLibBase1 Contract /// @author Enzyme Council <[emailย protected]> /// @notice A persistent contract containing all required storage variables and events /// for a GasRelayPaymasterLib /// @dev DO NOT EDIT CONTRACT ONCE DEPLOYED. If new events or storage are necessary, /// they should be added to a numbered GasRelayPaymasterLibBaseXXX that inherits the previous base. /// e.g., `GasRelayPaymasterLibBase2 is GasRelayPaymasterLibBase1` abstract contract GasRelayPaymasterLibBase1 { event Deposited(uint256 amount); event TransactionRelayed(address indexed authorizer, bytes4 invokedSelector, bool successful); event Withdrawn(uint256 amount); // Pseudo-constants address internal parentVault; } // 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 IProtocolFeeTracker Interface /// @author Enzyme Council <[emailย protected]> interface IProtocolFeeTracker { function initializeForVault(address) external; function payFee() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[emailย protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[emailย protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[emailย protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnRelayHub Interface /// @author Enzyme Council <[emailย protected]> interface IGsnRelayHub { function balanceOf(address target) external view returns (uint256); function calculateCharge(uint256 gasUsed, IGsnTypes.RelayData calldata relayData) external view returns (uint256); function depositFor(address target) external payable; function relayCall( uint256 maxAcceptanceBudget, IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function withdraw(uint256 amount, address payable dest) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[emailย protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[emailย protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[emailย protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[emailย protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[emailย protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title NonUpgradableProxy Contract /// @author Enzyme Council <[emailย protected]> /// @notice A proxy contract for use with non-upgradable libs /// @dev The recommended constructor-fallback pattern of a proxy in EIP-1822, updated for solc 0.6.12, /// and using an immutable lib value to save on gas (since not upgradable). /// The EIP-1967 storage slot for the lib is still assigned, /// for ease of referring to UIs that understand the pattern, i.e., Etherscan. abstract contract NonUpgradableProxy { address private immutable CONTRACT_LOGIC; constructor(bytes memory _constructData, address _contractLogic) public { CONTRACT_LOGIC = _contractLogic; assembly { // EIP-1967 slot: `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)` sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = CONTRACT_LOGIC; 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) } } } } // 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); } // 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. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[emailย protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Gets the string representation of the contract version (fulfills interface) return versionString_ The version string
function versionPaymaster() external view override returns (string memory versionString_) { return "2.2.3+opengsn.enzymefund.ipaymaster"; }
355,563
./partial_match/1/0x6b9e434b3e164EBc88c1f3cfAB8361C2d00a016e/sources/CTSellOffer.sol
Allows acceptance of sell offer contract by the buyer. Can only be called from GT Token contract/
function acceptOffer() external onlyTokenContract { offer.completed = true; offer.active = false; }
16,039,146
./partial_match/4/0x40B4d33637e7b50c08D5AfC6499F49f6DBb4caaC/sources/REVVInventory.sol
Transfers multiple tokens to another address Reverts if `ids` and `values` have inconsistent lengths. Reverts if `to` is the zero address. Reverts if the sender is not approved. Reverts if one of `ids` represents a non-fungible collection. Reverts if one of `ids` represents a non-fungible token and its paired `value` is not 1. Reverts if one of `ids` represents a non-fungible token and is not owned by `from`. Reverts if one of `ids` represents afungible token and its paired `value` is 0. Reverts if one of `ids` represents afungible token and `from` doesn't have enough balance. Emits an {IERC1155-TransferBatch} event. Emits up to several {IERC721-Transfer} events for each one of `ids` that represents a non-fungible token. from Current token owner. to Address of the new token owner. ids Identifiers of the tokens to transfer. values Amounts of tokens to transfer. data Optional data to pass to the receiver contract./
function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal virtual { require(to != address(0), "Inventory: transfer to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); uint256 nfCollectionId; uint256 nfCollectionCount; uint256 nftsCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; if (isFungible(id)) { _transferFungible(from, to, id, values[i], operatable); _transferNFT(from, to, id, values[i], operatable, true); emit Transfer(from, to, id); uint256 nextCollectionId = id & _NF_COLLECTION_MASK; if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; if (nextCollectionId != nfCollectionId) { transferNFTUpdateCollectionBalances(from, to, nfCollectionId, nfCollectionCount); nfCollectionId = nextCollectionId; nftsCount += nfCollectionCount; nfCollectionCount = 1; ++nfCollectionCount; } } revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { transferNFTUpdateCollectionBalances(from, to, nfCollectionId, nfCollectionCount); nftsCount += nfCollectionCount; transferNFTUpdateBalances(from, to, nftsCount); } emit TransferBatch(_msgSender(), from, to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(from, to, ids, values, data); } }
8,519,783
pragma solidity ^0.4.24; /* * gibmireinbier - Full Stack Blockchain Developer * 0xA4a799086aE18D7db6C4b57f496B081b44888888 * [email protected] */ /* CHANGELOGS: . GrandPot : 2 rewards per round 5% pot with winner rate 100%, no dividends, no fund to F2M contract 15% pot with winner rate dynamic, init at 1st round with rate = ((initGrandPot * 2 * 100 / 68) * avgMul / SLP) + 1000; push 12% to F2M contract (10% dividends, 2% fund) => everybody happy! // --REMOVED if total tickets > rate then 100% got winner no winner : increased in the next round got winner : decreased in the next round . Bounty : received 30% bought tickets of bountyhunter back in the next round instead of ETH (bonus tickets not included) . SBountys : received 10% bought tickets of sbountyhunter back in the next round instead of ETH (bonus tickets not included) claimable only in pending time between 2 rounds . 1% bought tickets as bonus to next round (1st buy turn) (bonus Tickets not included) . Jackpot: rates increased from (1/Rate1, 1/Rate2) to (1/(Rate1 - 1), 1/(Rate2 - 1)) after each buy and reseted if jackpot triggered. jackpot rate = (ethAmount / 0.1) * rate, max winrate = 1/2 no dividends, no fund to F2M contract . Ticketsnumbers start from 1 in every rounds . Multiplier system: . all tickets got same weight = 1 . 2 decimals in stead of 0 . Multi = (grandPot / initGrandPot) * x * y * z x = (11 - timer1) / 4 + 1 (unit = hour(s), max = 15/4) timer1 updated real time, but x got delay 60 seconds from last buy y = (6 - timer2) / 3 + 1 (unit = day(s), max = 3) z = 4 if isGoldenMin, else 1 GOLDEN MINUTE : realTime, set = 8 atm that means from x: 08 : 00 to x:08:59 is goldenMin and z = 4 . Waiting time between 2 rounds 24 hours -> 18 hours . addPot : 80% -> grandPot 10% -> majorPot 10% -> minorPot BUGS FIXED: . Jackpot rate increased with multi = ethAmount / 0.1 (ether) no more split buy required . GrandPot getWeightRange() problems AUTHORS: . Seizo : Tickets bonus per 100 tickets, setLastRound anytime remove pushDividend when grandPot, jackpot triggered, called only on tickets buying remove round0 . Clark : Multiplier system 0xd9cd43AD9cD04183b5083E9E6c8DD0CE0c08eDe3 . GMEB : Tickets bounty system, Math. formulas 0xA4a799086aE18D7db6C4b57f496B081b44888888 . Kuroo Hazama : Dynamic rate 0x1E55fa952FCBc1f917746277C9C99cf65D53EbC8 */ library Helper { using SafeMath for uint256; uint256 constant public ZOOM = 1000; uint256 constant public SDIVIDER = 3450000; uint256 constant public PDIVIDER = 3450000; uint256 constant public RDIVIDER = 1580000; // Starting LS price (SLP) uint256 constant public SLP = 0.002 ether; // Starting Added Time (SAT) uint256 constant public SAT = 30; // seconds // Price normalization (PN) uint256 constant public PN = 777; // EarlyIncome base uint256 constant public PBASE = 13; uint256 constant public PMULTI = 26; uint256 constant public LBase = 1; uint256 constant public ONE_HOUR = 3600; uint256 constant public ONE_DAY = 24 * ONE_HOUR; //uint256 constant public TIMEOUT0 = 3 * ONE_HOUR; uint256 constant public TIMEOUT1 = 12 * ONE_HOUR; uint256 constant public TIMEOUT2 = 7 * ONE_DAY; function bytes32ToString (bytes32 data) public pure returns (string) { bytes memory bytesString = new bytes(32); for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(data) * 2 ** (8 * j))); if (char != 0) { bytesString[j] = char; } } return string(bytesString); } function uintToBytes32(uint256 n) public pure returns (bytes32) { return bytes32(n); } function bytes32ToUint(bytes32 n) public pure returns (uint256) { return uint256(n); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToUint(string memory source) public pure returns (uint256) { return bytes32ToUint(stringToBytes32(source)); } function uintToString(uint256 _uint) public pure returns (string) { return bytes32ToString(uintToBytes32(_uint)); } /* function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) { bytes memory a = new bytes(end-begin+1); for(uint i = 0; i <= end - begin; i++){ a[i] = bytes(text)[i + begin - 1]; } return string(a); } */ function validUsername(string _username) public pure returns(bool) { uint256 len = bytes(_username).length; // Im Raum [4, 18] if ((len < 4) || (len > 18)) return false; // Letzte Char != ' ' if (bytes(_username)[len-1] == 32) return false; // Erste Char != '0' return uint256(bytes(_username)[0]) != 48; } // Lottery Helper // Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6 function getAddedTime(uint256 _rTicketSum, uint256 _tAmount) public pure returns (uint256) { //Luppe = 10000 = 10^4 uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 // div 10000^6 expo = expo / (10**24); if (expo > SAT) return 0; return (SAT - expo).mul(_tAmount); } function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime) public view returns(uint256) { uint256 _slideEndTime = (slideEndTime).add(toAddTime); uint256 timeout = _slideEndTime.sub(block.timestamp); // timeout capped at TIMEOUT1 if (timeout > TIMEOUT1) timeout = TIMEOUT1; _slideEndTime = (block.timestamp).add(timeout); // Capped at fixedEndTime if (_slideEndTime > fixedEndTime) return fixedEndTime; return _slideEndTime; } // get random in range [1, _range] with _seed function getRandom(uint256 _seed, uint256 _range) public pure returns(uint256) { if (_range == 0) return _seed; return (_seed % _range) + 1; } function getEarlyIncomeMul(uint256 _ticketSum) public pure returns(uint256) { // Early-Multiplier = 1 + PBASE / (1 + PMULTI * ((Current No. of LT)/RDIVIDER)^6) uint256 base = _ticketSum * ZOOM / RDIVIDER; uint256 expo = base.mul(base).mul(base); //^3 expo = expo.mul(expo) / (ZOOM**6); //^6 return (1 + PBASE / (1 + expo.mul(PMULTI))); } // get reveiced Tickets, based on current round ticketSum function getTAmount(uint256 _ethAmount, uint256 _ticketSum) public pure returns(uint256) { uint256 _tPrice = getTPrice(_ticketSum); return _ethAmount.div(_tPrice); } function isGoldenMin( uint256 _slideEndTime ) public view returns(bool) { uint256 _restTime1 = _slideEndTime.sub(block.timestamp); // golden min. exist if timer1 < 6 hours if (_restTime1 > 6 hours) return false; uint256 _min = (block.timestamp / 60) % 60; return _min == 8; } // percent ZOOM = 100, ie. mul = 2.05 return 205 // Lotto-Multiplier = ((grandPot / initGrandPot)^2) * x * y * z // x = (TIMEOUT1 - timer1 - 1) / 4 + 1 => (unit = hour, max = 11/4 + 1 = 3.75) // y = (TIMEOUT2 - timer2 - 1) / 3 + 1) => (unit = day max = 3) // z = isGoldenMin ? 4 : 1 function getTMul( uint256 _initGrandPot, uint256 _grandPot, uint256 _slideEndTime, uint256 _fixedEndTime ) public view returns(uint256) { uint256 _pZoom = 100; uint256 base = _initGrandPot != 0 ?_pZoom.mul(_grandPot) / _initGrandPot : _pZoom; uint256 expo = base.mul(base); uint256 _timer1 = _slideEndTime.sub(block.timestamp) / 1 hours; // 0.. 11 uint256 _timer2 = _fixedEndTime.sub(block.timestamp) / 1 days; // 0 .. 6 uint256 x = (_pZoom * (11 - _timer1) / 4) + _pZoom; // [1, 3.75] uint256 y = (_pZoom * (6 - _timer2) / 3) + _pZoom; // [1, 3] uint256 z = isGoldenMin(_slideEndTime) ? 4 : 1; uint256 res = expo.mul(x).mul(y).mul(z) / (_pZoom ** 3); // ~ [1, 90] return res; } // get ticket price, based on current round ticketSum //unit in ETH, no need / zoom^6 function getTPrice(uint256 _ticketSum) public pure returns(uint256) { uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 uint256 tPrice = SLP + expo / PN; return tPrice; } // used to draw grandpot results // weightRange = roundWeight * grandpot / (grandpot - initGrandPot) // grandPot = initGrandPot + round investedSum(for grandPot) function getWeightRange(uint256 initGrandPot) public pure returns(uint256) { uint256 avgMul = 30; return ((initGrandPot * 2 * 100 / 68) * avgMul / SLP) + 1000; } // dynamic rate _RATE = n // major rate = 1/n with _RATE = 1000 999 ... 1 // minor rate = 1/n with _RATE = 500 499 ... 1 // loop = _ethAmount / _MIN // lose rate = ((n- 1) / n) * ((n- 2) / (n - 1)) * ... * ((n- k) / (n - k + 1)) = (n - k) / n function isJackpot( uint256 _seed, uint256 _RATE, uint256 _MIN, uint256 _ethAmount ) public pure returns(bool) { // _RATE >= 2 uint256 k = _ethAmount / _MIN; if (k == 0) return false; // LOSE RATE MIN 50%, WIN RATE MAX 50% uint256 _loseCap = _RATE / 2; // IF _RATE - k > _loseCap if (_RATE > k + _loseCap) _loseCap = _RATE - k; bool _lose = (_seed % _RATE) < _loseCap; return !_lose; } } contract Lottery { using SafeMath for uint256; modifier withdrawRight(){ require(msg.sender == address(bankContract), "Bank only"); _; } modifier onlyDevTeam() { require(msg.sender == devTeam, "only for development team"); _; } modifier buyable() { require(block.timestamp > round[curRoundId].startTime, "not ready to sell Ticket"); require(block.timestamp < round[curRoundId].slideEndTime, "round over"); require(block.number <= round[curRoundId].keyBlockNr, "round over"); _; } modifier notStarted() { require(block.timestamp < round[curRoundId].startTime, "round started"); _; } enum RewardType { Minor, Major, Grand, Bounty } // 1 buy = 1 slot = _ethAmount => (tAmount, tMul) struct Slot { address buyer; uint256 rId; // ticket numbers in range and unique in all rounds uint256 tNumberFrom; uint256 tNumberTo; uint256 ethAmount; uint256 salt; } struct Round { // earlyIncome weight sum uint256 rEarlyIncomeWeight; // blockNumber to get hash as random seed uint256 keyBlockNr; mapping(address => bool) pBonusReceived; mapping(address => uint256) pBoughtTicketSum; mapping(address => uint256) pTicketSum; mapping(address => uint256) pInvestedSum; // early income weight by address mapping(address => uint256) pEarlyIncomeWeight; mapping(address => uint256) pEarlyIncomeCredit; mapping(address => uint256) pEarlyIncomeClaimed; // early income per weight uint256 ppw; // endTime increased every slot sold // endTime limited by fixedEndTime uint256 startTime; uint256 slideEndTime; uint256 fixedEndTime; // ticketSum from round 1 to this round uint256 ticketSum; // investedSum from round 1 to this round uint256 investedSum; // number of slots from round 1 to this round uint256 slotSum; } // round started with this grandPot amount, // used to calculate the rate for grandPot results // init in roundInit function uint256 public initGrandPot; Slot[] public slot; // slotId logs by address mapping( address => uint256[]) pSlot; mapping( address => uint256) public pSlotSum; // logs by address mapping( address => uint256) public pTicketSum; mapping( address => uint256) public pInvestedSum; CitizenInterface public citizenContract; F2mInterface public f2mContract; BankInterface public bankContract; RewardInterface public rewardContract; address public devTeam; uint256 constant public ZOOM = 1000; uint256 constant public ONE_HOUR = 60 * 60; uint256 constant public ONE_DAY = 24 * ONE_HOUR; uint256 constant public TIMEOUT0 = 3 * ONE_HOUR; uint256 constant public TIMEOUT1 = 12 * ONE_HOUR; uint256 constant public TIMEOUT2 = 7 * ONE_DAY; uint256 constant public FINALIZE_WAIT_DURATION = 60; // 60 Seconds uint256 constant public NEWROUND_WAIT_DURATION = 18 * ONE_HOUR; // 24 Hours // 15 seconds on Ethereum, 12 seconds used instead to make sure blockHash unavaiable // when slideEndTime reached // keyBlockNumber will be estimated again after every slot buy uint256 constant public BLOCK_TIME = 12; uint256 constant public MAX_BLOCK_DISTANCE = 250; uint256 constant public TBONUS_RATE = 100; uint256 public CASHOUT_REQ = 1; uint256 public GRAND_RATE; uint256 public MAJOR_RATE = 1001; uint256 public MINOR_RATE = 501; uint256 constant public MAJOR_MIN = 0.1 ether; uint256 constant public MINOR_MIN = 0.1 ether; //Bonus Tickets : Bounty + 7 sBounty uint256 public bountyPercent = 30; uint256 public sBountyPercent = 10; //uint256 public toNextPotPercent = 27; uint256 public grandRewardPercent = 15; uint256 public sGrandRewardPercent = 5; uint256 public jRewardPercent = 60; uint256 public toTokenPercent = 12; // 10% dividends 2% fund uint256 public toBuyTokenPercent = 1; uint256 public earlyIncomePercent = 22; uint256 public toRefPercent = 15; // sum == 100% = toPotPercent/100 * investedSum // uint256 public grandPercent = 80; //68; uint256 public majorPercent = 10; // 24; uint256 public minorPercent = 10; // 8; uint256 public grandPot; uint256 public majorPot; uint256 public minorPot; uint256 public curRoundId; uint256 public lastRoundId = 88888888; mapping (address => uint256) public rewardBalance; // used to save gas on earlyIncome calculating, curRoundId never included // only earlyIncome from round 1st to curRoundId-1 are fixed mapping (address => uint256) public lastWithdrawnRound; mapping (address => uint256) public earlyIncomeScannedSum; mapping (uint256 => Round) public round; // Current Round // first SlotId in last Block to fire jackpot uint256 public jSlot; // jackpot results of all slots in same block will be drawed at the same time, // by player, who buys the first slot in next block uint256 public lastBlockNr; // added by slot salt after every slot buy // does not matter with overflow uint256 public curRSalt; // ticket sum of current round uint256 public curRTicketSum; uint256 public lastBuyTime; uint256 public lastEndTime; uint256 constant multiDelayTime = 60; constructor (address _devTeam) public { // register address in network DevTeamInterface(_devTeam).setLotteryAddress(address(this)); devTeam = _devTeam; } // _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress]; function joinNetwork(address[6] _contract) public { require(address(citizenContract) == 0x0,"already setup"); f2mContract = F2mInterface(_contract[0]); bankContract = BankInterface(_contract[1]); citizenContract = CitizenInterface(_contract[2]); //lotteryContract = LotteryInterface(lotteryAddress); rewardContract = RewardInterface(_contract[4]); } function activeFirstRound() public onlyDevTeam() { require(curRoundId == 0, "already activated"); initRound(); GRAND_RATE = getWeightRange(); } // Core Functions function pushToPot() public payable { addPot(msg.value); } function checkpoint() private { // dummy slot between every 2 rounds // dummy slot never win jackpot cause of min 0.1 ETH Slot memory _slot; // _slot.tNumberTo = round[curRoundId].ticketSum; slot.push(_slot); Round memory _round; _round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp); // started with 3 hours timeout _round.slideEndTime = TIMEOUT0 + _round.startTime; _round.fixedEndTime = TIMEOUT2 + _round.startTime; _round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime); _round.ticketSum = round[curRoundId].ticketSum; _round.investedSum = round[curRoundId].investedSum; _round.slotSum = slot.length; curRoundId = curRoundId + 1; round[curRoundId] = _round; initGrandPot = grandPot; curRTicketSum = 0; } // from round 28+ function -- REMOVED function isLastRound() public view returns(bool) { return (curRoundId == lastRoundId); } function goNext() private { grandPot = 0; majorPot = 0; minorPot = 0; f2mContract.pushDividends.value(this.balance)(); // never start round[curRoundId].startTime = block.timestamp * 10; round[curRoundId].slideEndTime = block.timestamp * 10 + 1; CASHOUT_REQ = 0; } function initRound() private { // update all Round Log checkpoint(); if (isLastRound()) goNext(); updateMulti(); } function finalizeable() public view returns(bool) { uint256 finalizeTime = FINALIZE_WAIT_DURATION.add(round[curRoundId].slideEndTime); if (finalizeTime > block.timestamp) return false; // too soon to finalize if (getEstKeyBlockNr(curRoundId) >= block.number) return false; //block hash not exist return curRoundId > 0; } // bounty function finalize() public { require(finalizeable(), "Not ready to draw results"); uint256 _pRoundTicketSum = round[curRoundId].pBoughtTicketSum[msg.sender]; uint256 _bountyTicketSum = _pRoundTicketSum * bountyPercent / 100; endRound(msg.sender, _bountyTicketSum); initRound(); mintSlot(msg.sender, _bountyTicketSum, 0, 0); } function mintReward( address _lucker, uint256 _winNr, uint256 _slotId, uint256 _value, RewardType _rewardType) private { // add reward balance if its not Bounty Type and winner != 0x0 if ((_rewardType != RewardType.Bounty) && (_lucker != 0x0)) rewardBalance[_lucker] = rewardBalance[_lucker].add(_value); // reward log rewardContract.mintReward( _lucker, curRoundId, _winNr, slot[_slotId].tNumberFrom, slot[_slotId].tNumberTo, _value, uint256(_rewardType) ); } function mintSlot( address _buyer, // uint256 _rId, // ticket numbers in range and unique in all rounds // uint256 _tNumberFrom, // uint256 _tNumberTo, uint256 _tAmount, uint256 _ethAmount, uint256 _salt ) private { uint256 _tNumberFrom = curRTicketSum + 1; uint256 _tNumberTo = _tNumberFrom + _tAmount - 1; Slot memory _slot; _slot.buyer = _buyer; _slot.rId = curRoundId; _slot.tNumberFrom = _tNumberFrom; _slot.tNumberTo = _tNumberTo; _slot.ethAmount = _ethAmount; _slot.salt = _salt; slot.push(_slot); updateTicketSum(_buyer, _tAmount); round[curRoundId].slotSum = slot.length; pSlot[_buyer].push(slot.length - 1); } function jackpot() private { // get blocknumber to get blockhash uint256 keyBlockNr = getKeyBlockNr(lastBlockNr);//block.number; // salt not effected by jackpot, too risk uint256 seed = getSeed(keyBlockNr); // slot numberic from 1 ... totalSlot(round) // jackpot for all slot in last block, jSlot <= i <= lastSlotId (=slotSum - 1) // _to = first Slot in new block //uint256 _to = round[curRoundId].slotSum; uint256 jReward; // uint256 toF2mAmount; address winner; // jackpot check for slots in last block while (jSlot + 1 < round[curRoundId].slotSum) { // majorPot if (MAJOR_RATE > 2) MAJOR_RATE--; if (Helper.isJackpot(seed, MAJOR_RATE, MAJOR_MIN, slot[jSlot].ethAmount)){ winner = slot[jSlot].buyer; jReward = majorPot / 100 * jRewardPercent; mintReward(winner, 0, jSlot, jReward, RewardType.Major); majorPot = majorPot - jReward; MAJOR_RATE = 1001; } seed = seed + jSlot; // minorPot if (MINOR_RATE > 2) MINOR_RATE--; if (Helper.isJackpot(seed, MINOR_RATE, MINOR_MIN, slot[jSlot].ethAmount)){ winner = slot[jSlot].buyer; jReward = minorPot / 100 * jRewardPercent; mintReward(winner, 0, jSlot, jReward, RewardType.Minor); minorPot = minorPot - jReward; MINOR_RATE = 501; } seed = seed + jSlot; jSlot++; } } function endRound(address _bountyHunter, uint256 _bountyTicketSum) private { // GRAND_RATE = GRAND_RATE * 9 / 10; // REMOVED uint256 _rId = curRoundId; uint256 keyBlockNr = getKeyBlockNr(round[_rId].keyBlockNr); // curRSalt SAFE, CHECKED uint256 _seed = getSeed(keyBlockNr) + curRSalt; uint256 onePercent = grandPot / 100; // 0 : 5% grandPot, 100% winRate // 1 : 15% grandPot, dynamic winRate uint256[2] memory rGrandReward = [ onePercent * sGrandRewardPercent, onePercent * grandRewardPercent ]; uint256[2] memory weightRange = [ curRTicketSum, GRAND_RATE > curRTicketSum ? GRAND_RATE : curRTicketSum ]; // REMOVED // uint256[2] memory toF2mAmount = [0, onePercent * toTokenPercent]; // 1st turn for small grandPot (val = 5% rate = 100%) // 2nd turn for big grandPot (val = 15%, rate = max(GRAND_RATE, curRTicketSum), 12% to F2M contract if got winner) for (uint256 i = 0; i < 2; i++){ address _winner = 0x0; uint256 _winSlot = 0; uint256 _winNr = Helper.getRandom(_seed, weightRange[i]); // if winNr > curRTicketSum => no winner this turn // win Slot : fromWeight <= winNr <= toWeight // got winner this rolling turn if (_winNr <= curRTicketSum) { // grandPot -= rGrandReward[i] + toF2mAmount[i]; grandPot -= rGrandReward[i]; // big grandPot 15% if (i == 1) { GRAND_RATE = GRAND_RATE * 2; // f2mContract.pushDividends.value(toF2mAmount[i])(); } _winSlot = getWinSlot(_winNr); _winner = slot[_winSlot].buyer; _seed = _seed + (_seed / 10); } mintReward(_winner, _winNr, _winSlot, rGrandReward[i], RewardType.Grand); } mintReward(_bountyHunter, 0, 0, _bountyTicketSum, RewardType.Bounty); rewardContract.resetCounter(curRoundId); GRAND_RATE = (GRAND_RATE / 100) * 99 + 1; } function buy(string _sSalt) public payable { buyFor(_sSalt, msg.sender); } function updateInvested(address _buyer, uint256 _ethAmount) private { round[curRoundId].investedSum += _ethAmount; round[curRoundId].pInvestedSum[_buyer] += _ethAmount; pInvestedSum[_buyer] += _ethAmount; } function updateTicketSum(address _buyer, uint256 _tAmount) private { round[curRoundId].ticketSum = round[curRoundId].ticketSum + _tAmount; round[curRoundId].pTicketSum[_buyer] = round[curRoundId].pTicketSum[_buyer] + _tAmount; curRTicketSum = curRTicketSum + _tAmount; pTicketSum[_buyer] = pTicketSum[_buyer] + _tAmount; } function updateEarlyIncome(address _buyer, uint256 _pWeight) private { round[curRoundId].rEarlyIncomeWeight = _pWeight.add(round[curRoundId].rEarlyIncomeWeight); round[curRoundId].pEarlyIncomeWeight[_buyer] = _pWeight.add(round[curRoundId].pEarlyIncomeWeight[_buyer]); round[curRoundId].pEarlyIncomeCredit[_buyer] = round[curRoundId].pEarlyIncomeCredit[_buyer].add(_pWeight.mul(round[curRoundId].ppw)); } function getBonusTickets(address _buyer) private returns(uint256) { if (round[curRoundId].pBonusReceived[_buyer]) return 0; round[curRoundId].pBonusReceived[_buyer] = true; return round[curRoundId - 1].pBoughtTicketSum[_buyer] / TBONUS_RATE; } function updateMulti() private { if (lastBuyTime + multiDelayTime < block.timestamp) { lastEndTime = round[curRoundId].slideEndTime; } lastBuyTime = block.timestamp; } function buyFor(string _sSalt, address _sender) public payable buyable() { uint256 _salt = Helper.stringToUint(_sSalt); uint256 _ethAmount = msg.value; uint256 _ticketSum = curRTicketSum; require(_ethAmount >= Helper.getTPrice(_ticketSum), "not enough to buy 1 ticket"); // investedSum logs updateInvested(_sender, _ethAmount); updateMulti(); // update salt curRSalt = curRSalt + _salt; uint256 _tAmount = Helper.getTAmount(_ethAmount, _ticketSum); uint256 _tMul = getTMul(); // 100x Zoomed uint256 _pMul = Helper.getEarlyIncomeMul(_ticketSum); uint256 _pWeight = _pMul.mul(_tAmount); uint256 _toAddTime = Helper.getAddedTime(_ticketSum, _tAmount); addTime(curRoundId, _toAddTime); _tAmount = _tAmount.mul(_tMul) / 100; round[curRoundId].pBoughtTicketSum[_sender] += _tAmount; mintSlot(_sender, _tAmount + getBonusTickets(_sender), _ethAmount, _salt); // EarlyIncome Weight // ppw and credit zoomed x1000 // earlyIncome mul of each ticket in this slot updateEarlyIncome(_sender, _pWeight); // first slot in this block draw jacpot results for // all slot in last block if (lastBlockNr != block.number) { jackpot(); lastBlockNr = block.number; } distributeSlotBuy(_sender, curRoundId, _ethAmount); round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime); } function distributeSlotBuy(address _sender, uint256 _rId, uint256 _ethAmount) private { uint256 onePercent = _ethAmount / 100; uint256 toF2mAmount = onePercent * toTokenPercent; // 12 uint256 toRefAmount = onePercent * toRefPercent; // 10 uint256 toBuyTokenAmount = onePercent * toBuyTokenPercent; //1 uint256 earlyIncomeAmount = onePercent * earlyIncomePercent; //27 uint256 taxAmount = toF2mAmount + toRefAmount + toBuyTokenAmount + earlyIncomeAmount; // 50 uint256 taxedEthAmount = _ethAmount.sub(taxAmount); // 50 addPot(taxedEthAmount); // 10% Ref citizenContract.pushRefIncome.value(toRefAmount)(_sender); // 2% Fund + 10% Dividends f2mContract.pushDividends.value(toF2mAmount)(); // 1% buy Token f2mContract.buyFor.value(toBuyTokenAmount)(_sender); // 27% Early uint256 deltaPpw = (earlyIncomeAmount * ZOOM).div(round[_rId].rEarlyIncomeWeight); round[_rId].ppw = deltaPpw.add(round[_rId].ppw); } function claimEarlyIncomebyAddress(address _buyer) private { if (curRoundId == 0) return; claimEarlyIncomebyAddressRound(_buyer, curRoundId); uint256 _rId = curRoundId - 1; while ((_rId > lastWithdrawnRound[_buyer]) && (_rId + 20 > curRoundId)) { earlyIncomeScannedSum[_buyer] += claimEarlyIncomebyAddressRound(_buyer, _rId); _rId = _rId - 1; } } function claimEarlyIncomebyAddressRound(address _buyer, uint256 _rId) private returns(uint256) { uint256 _amount = getCurEarlyIncomeByAddressRound(_buyer, _rId); if (_amount == 0) return 0; round[_rId].pEarlyIncomeClaimed[_buyer] = _amount.add(round[_rId].pEarlyIncomeClaimed[_buyer]); rewardBalance[_buyer] = _amount.add(rewardBalance[_buyer]); return _amount; } function withdrawFor(address _sender) public withdrawRight() returns(uint256) { if (curRoundId == 0) return; claimEarlyIncomebyAddress(_sender); lastWithdrawnRound[_sender] = curRoundId - 1; uint256 _amount = rewardBalance[_sender]; rewardBalance[_sender] = 0; bankContract.pushToBank.value(_amount)(_sender); return _amount; } function addTime(uint256 _rId, uint256 _toAddTime) private { round[_rId].slideEndTime = Helper.getNewEndTime(_toAddTime, round[_rId].slideEndTime, round[_rId].fixedEndTime); } // distribute to 3 pots Grand, Majorm Minor function addPot(uint256 _amount) private { uint256 onePercent = _amount / 100; uint256 toMinor = onePercent * minorPercent; uint256 toMajor = onePercent * majorPercent; uint256 toGrand = _amount - toMinor - toMajor; minorPot = minorPot + toMinor; majorPot = majorPot + toMajor; grandPot = grandPot + toGrand; } ////////////////////////////////////////////////////////////////// // READ FUNCTIONS ////////////////////////////////////////////////////////////////// function isWinSlot(uint256 _slotId, uint256 _keyNumber) public view returns(bool) { return (slot[_slotId - 1].tNumberTo < _keyNumber) && (slot[_slotId].tNumberTo >= _keyNumber); } function getWeightRange() public view returns(uint256) { return Helper.getWeightRange(initGrandPot); } function getWinSlot(uint256 _keyNumber) public view returns(uint256) { // return 0 if not found uint256 _to = slot.length - 1; uint256 _from = round[curRoundId-1].slotSum + 1; // dummy slot ignore uint256 _pivot; //Slot memory _slot; uint256 _pivotTo; // Binary search while (_from <= _to) { _pivot = (_from + _to) / 2; _pivotTo = slot[_pivot].tNumberTo; if (isWinSlot(_pivot, _keyNumber)) return _pivot; if (_pivotTo < _keyNumber) { // in right side _from = _pivot + 1; } else { // in left side _to = _pivot - 1; } } return _pivot; // never happens or smt gone wrong } // Key Block in future function genEstKeyBlockNr(uint256 _endTime) public view returns(uint256) { if (block.timestamp >= _endTime) return block.number + 8; uint256 timeDist = _endTime - block.timestamp; uint256 estBlockDist = timeDist / BLOCK_TIME; return block.number + estBlockDist + 8; } // get block hash of first block with blocktime > _endTime function getSeed(uint256 _keyBlockNr) public view returns (uint256) { // Key Block not mined atm if (block.number <= _keyBlockNr) return block.number; return uint256(blockhash(_keyBlockNr)); } // current reward balance function getRewardBalance(address _buyer) public view returns(uint256) { return rewardBalance[_buyer]; } // GET endTime function getSlideEndTime(uint256 _rId) public view returns(uint256) { return(round[_rId].slideEndTime); } function getFixedEndTime(uint256 _rId) public view returns(uint256) { return(round[_rId].fixedEndTime); } function getTotalPot() public view returns(uint256) { return grandPot + majorPot + minorPot; } // EarlyIncome function getEarlyIncomeByAddress(address _buyer) public view returns(uint256) { uint256 _sum = earlyIncomeScannedSum[_buyer]; uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1 if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100; uint256 _rId = _fromRound; while (_rId <= curRoundId) { _sum = _sum + getEarlyIncomeByAddressRound(_buyer, _rId); _rId++; } return _sum; } // included claimed amount function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256) { uint256 _pWeight = round[_rId].pEarlyIncomeWeight[_buyer]; uint256 _ppw = round[_rId].ppw; uint256 _rCredit = round[_rId].pEarlyIncomeCredit[_buyer]; uint256 _rEarlyIncome = ((_ppw.mul(_pWeight)).sub(_rCredit)).div(ZOOM); return _rEarlyIncome; } function getCurEarlyIncomeByAddress(address _buyer) public view returns(uint256) { uint256 _sum = 0; uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1 if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100; uint256 _rId = _fromRound; while (_rId <= curRoundId) { _sum = _sum.add(getCurEarlyIncomeByAddressRound(_buyer, _rId)); _rId++; } return _sum; } function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256) { uint256 _rEarlyIncome = getEarlyIncomeByAddressRound(_buyer, _rId); return _rEarlyIncome.sub(round[_rId].pEarlyIncomeClaimed[_buyer]); } //////////////////////////////////////////////////////////////////// function getEstKeyBlockNr(uint256 _rId) public view returns(uint256) { return round[_rId].keyBlockNr; } function getKeyBlockNr(uint256 _estKeyBlockNr) public view returns(uint256) { require(block.number > _estKeyBlockNr, "blockHash not avaiable"); uint256 jump = (block.number - _estKeyBlockNr) / MAX_BLOCK_DISTANCE * MAX_BLOCK_DISTANCE; return _estKeyBlockNr + jump; } // Logs function getCurRoundId() public view returns(uint256) { return curRoundId; } function getTPrice() public view returns(uint256) { return Helper.getTPrice(curRTicketSum); } function getTMul() public view returns(uint256) { return Helper.getTMul( initGrandPot, grandPot, lastBuyTime + multiDelayTime < block.timestamp ? round[curRoundId].slideEndTime : lastEndTime, round[curRoundId].fixedEndTime ); } function getPMul() public view returns(uint256) { return Helper.getEarlyIncomeMul(curRTicketSum); } function getPTicketSumByRound(uint256 _rId, address _buyer) public view returns(uint256) { return round[_rId].pTicketSum[_buyer]; } function getTicketSumToRound(uint256 _rId) public view returns(uint256) { return round[_rId].ticketSum; } function getPInvestedSumByRound(uint256 _rId, address _buyer) public view returns(uint256) { return round[_rId].pInvestedSum[_buyer]; } function getInvestedSumToRound(uint256 _rId) public view returns(uint256) { return round[_rId].investedSum; } function getPSlotLength(address _sender) public view returns(uint256) { return pSlot[_sender].length; } function getSlotLength() public view returns(uint256) { return slot.length; } function getSlotId(address _sender, uint256 i) public view returns(uint256) { return pSlot[_sender][i]; } function getSlotInfo(uint256 _slotId) public view returns(address, uint256[4], string) { Slot memory _slot = slot[_slotId]; return (_slot.buyer,[_slot.rId, _slot.tNumberFrom, _slot.tNumberTo, _slot.ethAmount], Helper.uintToString(_slot.salt)); } function cashoutable(address _address) public view returns(bool) { // need 1 ticket of curRound or lastRound in waiting time to start new round if (round[curRoundId].pTicketSum[_address] >= CASHOUT_REQ) return true; if (round[curRoundId].startTime > block.timestamp) { // underflow return false uint256 _lastRoundTickets = getPTicketSumByRound(curRoundId - 1, _address); if (_lastRoundTickets >= CASHOUT_REQ) return true; } return false; } // set endRound, prepare to upgrade new version function setLastRound(uint256 _lastRoundId) public onlyDevTeam() { require(_lastRoundId >= 8 && _lastRoundId > curRoundId, "too early to end"); require(lastRoundId == 88888888, "already set"); lastRoundId = _lastRoundId; } function sBountyClaim(address _sBountyHunter) public notStarted() returns(uint256) { require(msg.sender == address(rewardContract), "only Reward contract can manage sBountys"); uint256 _lastRoundTickets = round[curRoundId - 1].pBoughtTicketSum[_sBountyHunter]; uint256 _sBountyTickets = _lastRoundTickets * sBountyPercent / 100; mintSlot(_sBountyHunter, _sBountyTickets, 0, 0); return _sBountyTickets; } /* TEST */ // function forceEndRound() // public // { // round[curRoundId].keyBlockNr = block.number; // round[curRoundId].slideEndTime = block.timestamp; // round[curRoundId].fixedEndTime = block.timestamp; // } // function setTimer1(uint256 _hours) // public // { // round[curRoundId].slideEndTime = block.timestamp + _hours * 1 hours + 60; // round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime); // } // function setTimer2(uint256 _days) // public // { // round[curRoundId].fixedEndTime = block.timestamp + _days * 1 days + 60; // require(round[curRoundId].fixedEndTime >= round[curRoundId].slideEndTime, "invalid test data"); // } } interface F2mInterface { function joinNetwork(address[6] _contract) public; // one time called // function disableRound0() public; function activeBuy() public; // function premine() public; // Dividends from all sources (DApps, Donate ...) function pushDividends() public payable; /** * Converts all of caller's dividends to tokens. */ function buyFor(address _buyer) public payable; function sell(uint256 _tokenAmount) public; function exit() public; function devTeamWithdraw() public returns(uint256); function withdrawFor(address sender) public returns(uint256); function transfer(address _to, uint256 _tokenAmount) public returns(bool); /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function setAutoBuy() public; /*========================================== = PUBLIC FUNCTIONS = ==========================================*/ function ethBalance(address _address) public view returns(uint256); function myBalance() public view returns(uint256); function myEthBalance() public view returns(uint256); function swapToken() public; function setNewToken(address _newTokenAddress) public; } interface CitizenInterface { function joinNetwork(address[6] _contract) public; /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function devTeamWithdraw() public; /*---------- WRITE FUNCTIONS ----------*/ function updateUsername(string _sNewUsername) public; //Sources: Token contract, DApps function pushRefIncome(address _sender) public payable; function withdrawFor(address _sender) public payable returns(uint256); function devTeamReinvest() public returns(uint256); /*---------- READ FUNCTIONS ----------*/ function getRefWallet(address _address) public view returns(uint256); } interface DevTeamInterface { function setF2mAddress(address _address) public; function setLotteryAddress(address _address) public; function setCitizenAddress(address _address) public; function setBankAddress(address _address) public; function setRewardAddress(address _address) public; function setWhitelistAddress(address _address) public; function setupNetwork() public; } interface BankInterface { function joinNetwork(address[6] _contract) public; function pushToBank(address _player) public payable; } interface RewardInterface { function mintReward( address _lucker, uint256 curRoundId, uint256 _winNr, uint256 _tNumberFrom, uint256 _tNumberTo, uint256 _value, uint256 _rewardType) public; function joinNetwork(address[6] _contract) public; function pushBounty(uint256 _curRoundId) public payable; function resetCounter(uint256 _curRoundId) public; } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
used to draw grandpot results weightRange = roundWeight grandpot / (grandpot - initGrandPot) grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 initGrandPot) public pure returns(uint256) { uint256 avgMul = 30; return ((initGrandPot * 2 * 100 / 68) * avgMul / SLP) + 1000; }
887,379
pragma solidity ^0.5.11; pragma experimental ABIEncoderV2; contract STOEscrowBox { address public authCertVoucherLedgerAddress; address public userCertVoucherLedgerAddress; struct Vote { bool _created; bool _passed; bool _executed; bool _cancelled; uint256 _voteNum; address _ledger; uint256 _value; address _from; address _to; bytes _calldata; } mapping(bytes32 => Vote) public voteMap; uint256 public authNum; event ProposeCreated (bytes32 indexed _id); event ProposePassed (bytes32 indexed _id); event ProposeExecuted (bytes32 indexed _id); event ProposeCancelled (bytes32 indexed _id); constructor(address _authCertVoucherLedgerAddress, address _userCertVoucherLedgerAddress) public { authNum = 1; authCertVoucherLedgerAddress = _authCertVoucherLedgerAddress; userCertVoucherLedgerAddress = _userCertVoucherLedgerAddress; } function setAuthNum (uint256 _authNum) public returns (bool) { require(msg.sender == address(this)); authNum = _authNum; return true; } function setAuthCertVoucherLedgerAddress (address _addr) public returns (bool) { require(msg.sender == address(this)); authCertVoucherLedgerAddress = _addr; return true; } function setUserCertVoucherLedgerAddress (address _addr) public returns (bool) { require(msg.sender == address(this)); userCertVoucherLedgerAddress = _addr; return true; } function getLedgerBalanceHumanNumber (address _ledgerAddress, address _holderAddress) public view returns (uint256) { (bool _success, bytes memory _returnData1) = _ledgerAddress.staticcall( abi.encodeWithSelector( bytes4(keccak256(bytes("balanceOf(address)"))), _holderAddress)); require(_success); (uint256 _balance) = abi.decode(_returnData1, (uint256)); return _balance; } function encodePropose (uint256 _value, address _from, uint256 _mode, bytes memory _data) public pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256(bytes("propose(uint256,address,uint256,bytes)"))), _value, _from, _mode, _data); } function decodePropose (bytes memory __data) public pure returns (uint256 _value, address _from, uint256 _mode, bytes memory _data) { (_value, _from, _mode, _data) = abi.decode(__data, (uint256, address, uint256, bytes)); } function encodeCallData (bytes32 _voteHash, address _to, bytes memory _calldata) public pure returns (bytes memory) { return abi.encode(_voteHash, _to, _calldata); } function decodeCallData (bytes memory _data) public pure returns (bytes32 _voteHash, address _to, bytes memory _calldata) { (_voteHash, _to, _calldata) = abi.decode(_data, (bytes32, address, bytes)); } // anyone holds userCert proposes function mode_0 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require( getLedgerBalanceHumanNumber(userCertVoucherLedgerAddress, _from) > 0 || getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash, address _to, bytes memory _calldata) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._created == false); _voteObj._created = true; _voteObj._voteNum = 0; _voteObj._ledger = _ledger; _voteObj._value = _value; _voteObj._from = _from; _voteObj._to = _to; _voteObj._calldata = _calldata; emit ProposeCreated(_voteHash); return true; } // auth accept function mode_1 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require(getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash,,) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._voteNum <= authNum && _voteObj._passed == false && _voteObj._cancelled == false); _voteObj._voteNum++; if (_voteObj._voteNum == authNum) { (bool success1,) = _voteObj._to.call(_voteObj._calldata); require(success1); _voteObj._passed = true; emit ProposePassed(_voteHash); (bool success2,) = address(this).call( abi.encodeWithSelector( bytes4(keccak256(bytes("finalise(bytes32)"))), _voteHash)); require(success2); } return true; } // auth reject or timeout function mode_2 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require(getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash,,) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._voteNum <= authNum && _voteObj._passed == false && _voteObj._cancelled == false); (bool success1,) = _voteObj._ledger.call( abi.encodeWithSelector( bytes4(keccak256(bytes("transfer(address,uint256)"))), _voteObj._from, _voteObj._value)); require(success1); (bool success2,) = address(this).call( abi.encodeWithSelector( bytes4(keccak256(bytes("cancel(bytes32)"))), _voteHash)); require(success2); return true; } function propose (uint256 _value, address _from, uint256 _mode, bytes calldata _data) external returns (bool) { if (_mode == 0) { require(mode_0(msg.sender, _value, _from, _data)); } return true; } function negotiate (uint256 _value, address _from, uint256 _mode, bytes calldata _data) external returns (bool) { if (_mode == 1) { require(mode_1(msg.sender, _value, _from, _data)); } if (_mode == 2) { require(mode_2(msg.sender, _value, _from, _data)); } return true; } function finalise (bytes32 _voteHash) external returns (bool) { require(msg.sender == address(this)); Vote storage _voteObj = voteMap[_voteHash]; _voteObj._executed = true; emit ProposeExecuted(_voteHash); return true; } function cancel (bytes32 _voteHash) external returns (bool) { require(msg.sender == address(this)); Vote storage _voteObj = voteMap[_voteHash]; _voteObj._cancelled = true; emit ProposeCancelled(_voteHash); return true; } }
anyone holds userCert proposes
function mode_0 (address _ledger, uint256 _value, address _from, bytes memory _data) private returns (bool) { require( getLedgerBalanceHumanNumber(userCertVoucherLedgerAddress, _from) > 0 || getLedgerBalanceHumanNumber(authCertVoucherLedgerAddress, _from) > 0); (bytes32 _voteHash, address _to, bytes memory _calldata) = abi.decode(_data, (bytes32, address, bytes)); Vote storage _voteObj = voteMap[_voteHash]; require(_voteObj._created == false); _voteObj._created = true; _voteObj._voteNum = 0; _voteObj._ledger = _ledger; _voteObj._value = _value; _voteObj._from = _from; _voteObj._to = _to; _voteObj._calldata = _calldata; emit ProposeCreated(_voteHash); return true; }
7,281,352
./partial_match/42/0x1714642791bca216fd5A46f5F7F908558DA093b3/sources/STYK_I.sol
Alias of sell() and withdraw()./ get token count for caller & sell them all
function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); userAdded[_customerAddress] = false; uint256 index = getUserAddressIndex(_customerAddress); address _lastAddress = userAddress[userAddress.length - 1]; uint256 _lastindex = getUserAddressIndex(_lastAddress); userAddress[index] = _lastAddress; userAddress[userAddress.length - 1] = _customerAddress; userIndex[_lastAddress] = index; userIndex[_customerAddress] = _lastindex; delete userIndex[_customerAddress]; userAddress.pop(); userCount--; }
3,453,128
./partial_match/1/0x3CF90663216378760b3f841b20cA19C5c39795cc/sources/FadedArcade.sol
Returns the root of a tree reconstructed from `leaves` and the sibling nodes in `proof`, consuming from one or the other at each step according to the instructions given by `proofFlags`. _Available since v4.7._/ This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of the merkle tree. Check proof validity. The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". At each step, we compute the next hash using two values: - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we get the next hash. - depending on the flag, either another value for the "main queue" (merging branches) or an element from the `proof` array.
function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; require( leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof" ); bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; return leaves[0]; return proof[0]; } }
2,678,337
./full_match/5/0xA0E69f8Cf9f8F8555e1Bd0983214871e674ac30F/sources/contracts/tenderswap/TenderSwap.sol
@inheritdoc ITenderSwap
function removeLiquidityImbalance( uint256[2] calldata _amounts, uint256 _maxBurnAmount, uint256 _deadline ) external override nonReentrant deadlineCheck(_deadline) returns (uint256) { SwapUtils.PooledToken[2] memory tokens_ = [token0, token1]; return SwapUtils.removeLiquidityImbalance( tokens_, _amounts, _maxBurnAmount, amplificationParams, feeParams, lpToken ); }
7,038,727
./full_match/11155111/0x5d78a75E1adaBe80AC410D4b4aEAF68c9D78B6d2/sources/contracts/interfaces/IDiamondLoupe.sol
A loupe is a small magnifying glass used to look at diamonds. These functions look at diamonds
interface IDiamondLoupe { pragma solidity ^0.8.21; struct Facet { address facetAddress; bytes4[] functionSelectors; } }
3,806,441
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/utils/cryptography/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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 @chainlink/contracts/src/v0.8/interfaces/[email protected] pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // File @chainlink/contracts/src/v0.8/[email protected] pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File @chainlink/contracts/src/v0.8/[email protected] pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall( vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER) ); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed( _keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash] ); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/token/ERC721/ERC721.sol // Creators: locationtba.eth, 2pmflow.eth pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */ abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = 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, owner); } /** * @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 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721: token already minted"); require(quantity <= maxBatchSize, "ERC721: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721: transfer from incorrect owner" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/SquirrellySquirrels.sol // โ–ˆโ–ˆ // โ–ˆโ–ˆ // โ–ˆโ–ˆ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ // โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’ // โ–’โ–’โ–’โ–’โ–’โ–’ // // ____ ___ _ _ ___ ____ ____ _____ _ _ __ __ // / ___| / _ \| | | |_ _| _ \| _ \| ____| | | | \ \ / / // \___ \| | | | | | || || |_) | |_) | _| | | | | \ V / // ___) | |_| | |_| || || _ <| _ <| |___| |___| |___| | // |____/ \__\_\\___/|___|_| \_\_| \_\_____|_____|_____|_| // // ____ ___ _ _ ___ ____ ____ _____ _ ____ // / ___| / _ \| | | |_ _| _ \| _ \| ____| | / ___| // \___ \| | | | | | || || |_) | |_) | _| | | \___ \ // ___) | |_| | |_| || || _ <| _ <| |___| |___ ___) | // |____/ \__\_\\___/|___|_| \_\_| \_\_____|_____|____/ pragma solidity ^0.8.0; contract SquirrellySquirrels is VRFConsumerBase, ERC721, Ownable { using Strings for uint256; uint256 public constant NFT_1_PRICE = 0.16 ether; uint256 public constant NFT_3_PRICE = 0.39 ether; uint256 public constant NFT_5_PRICE = 0.45 ether; uint256 public constant MAX_NFT_PURCHASE_PRESALE = 5; uint256 public constant MAX_MINT_PER_TX = 5; uint256 public constant MAX_SUPPLY = 10000; bool public saleIsActive = false; bool public presaleIsActive = false; bool public revealed = false; uint256 public reserve = 300; uint256 public startingIndex; mapping(address => uint256) public allowListNumClaimed; bytes32 public allowListMerkleRoot; bytes32 public startingIndexRequestId; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri = ""; string public provenance; string private _baseURIExtended; modifier mintCompliance(uint256 _numberOfTokens) { require( _numberOfTokens > 0 && _numberOfTokens != 2 && _numberOfTokens != 4 && _numberOfTokens <= MAX_MINT_PER_TX, "Invalid mint amount" ); require( (_numberOfTokens == 1 && msg.value == NFT_1_PRICE) || (_numberOfTokens == 3 && msg.value == NFT_3_PRICE) || (_numberOfTokens == 5 && msg.value == NFT_5_PRICE), "Sent ether value is incorrect" ); _; } constructor( address _vrfCoordinator, address _link, address _owner ) ERC721("Squirrelly Squirrels", "SQRLY", 300) VRFConsumerBase(_vrfCoordinator, _link) { transferOwnership(_owner); } function requestStartingIndex(bytes32 _keyHash, uint256 _fee) external onlyOwner returns (bytes32 requestId) { require(startingIndex == 0, "startingIndex has already been set"); bytes32 _requestId = requestRandomness(_keyHash, _fee); startingIndexRequestId = _requestId; return _requestId; } function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override { if (startingIndexRequestId == _requestId) { startingIndex = _randomness % MAX_SUPPLY; } } function claimReserve(address _to, uint256 _reserveAmount) external onlyOwner { require( _reserveAmount > 0 && _reserveAmount <= reserve, "Not enough reserve left for team" ); reserve = reserve - _reserveAmount; _safeMint(_to, _reserveAmount); } function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function flipPresaleState() external onlyOwner { presaleIsActive = !presaleIsActive; } function isAllowListed(bytes32[] memory _proof, address _address) public view returns (bool) { require(_address != address(0), "Zero address not on Allow List"); bytes32 leaf = keccak256(abi.encodePacked(_address)); return MerkleProof.verify(_proof, allowListMerkleRoot, leaf); } function setAllowListMerkleRoot(bytes32 _allowListMerkleRoot) external onlyOwner { allowListMerkleRoot = _allowListMerkleRoot; } function mintPresale(bytes32[] memory _proof, uint256 _numberOfTokens) external payable mintCompliance(_numberOfTokens) { require(presaleIsActive, "Presale is not active at the moment"); require( isAllowListed(_proof, msg.sender), "This address is not allow listed for the presale" ); require( allowListNumClaimed[msg.sender] + _numberOfTokens <= MAX_NFT_PURCHASE_PRESALE, "Exceeds allowed presale you can mint" ); require( totalSupply() + _numberOfTokens <= MAX_SUPPLY - reserve, "Purchase would exceed max supply" ); _safeMint(msg.sender, _numberOfTokens); allowListNumClaimed[msg.sender] += _numberOfTokens; } function mint(uint256 _numberOfTokens) external payable mintCompliance(_numberOfTokens) { require(saleIsActive, "Sale is not active at the moment"); require( totalSupply() + _numberOfTokens <= MAX_SUPPLY - reserve, "Purchase would exceed max supply" ); _safeMint(msg.sender, _numberOfTokens); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); for (uint256 i = 0; i < ownerTokenCount; i++) { ownedTokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix) ) : ""; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) external onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) external onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) external onlyOwner { uriSuffix = _uriSuffix; } function setRevealed(bool _state) external onlyOwner { revealed = _state; } function setProvenance(string calldata _provenance) external onlyOwner { provenance = _provenance; } function withdraw() external onlyOwner { (bool os, ) = payable(owner()).call{ value: address(this).balance }(""); require(os, "withdraw: transfer failed"); } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); 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 owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } }
1,102,762
pragma solidity 0.5.7; import 'openzeppelin-eth/contracts/ownership/Ownable.sol'; import './MixinKeys.sol'; import './MixinLockCore.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './MixinFunds.sol'; contract MixinRefunds is Ownable, MixinFunds, MixinLockCore, MixinKeys { using SafeMath for uint; // CancelAndRefund will return funds based on time remaining minus this penalty. // This is calculated as `proRatedRefund * refundPenaltyNumerator / refundPenaltyDenominator`. uint public refundPenaltyNumerator = 1; uint public refundPenaltyDenominator = 10; event CancelKey( uint indexed tokenId, address indexed owner, uint refund ); event RefundPenaltyChanged( uint oldRefundPenaltyNumerator, uint oldRefundPenaltyDenominator, uint refundPenaltyNumerator, uint refundPenaltyDenominator ); /** * @dev Destroys the user's key and sends a refund based on the amount of time remaining. */ function cancelAndRefund() external { Key storage key = _getKeyFor(msg.sender); uint refund = _getCancelAndRefundValue(msg.sender); emit CancelKey(key.tokenId, msg.sender, refund); // expirationTimestamp is a proxy for hasKey, setting this to `block.timestamp` instead // of 0 so that we can still differentiate hasKey from hasValidKey. key.expirationTimestamp = block.timestamp; if (refund > 0) { // Security: doing this last to avoid re-entrancy concerns _transfer(msg.sender, refund); } } /** * Allow the owner to change the refund penalty. */ function updateRefundPenalty( uint _refundPenaltyNumerator, uint _refundPenaltyDenominator ) external onlyOwner { require(_refundPenaltyDenominator != 0, 'INVALID_RATE'); emit RefundPenaltyChanged( refundPenaltyNumerator, refundPenaltyDenominator, _refundPenaltyNumerator, _refundPenaltyDenominator ); refundPenaltyNumerator = _refundPenaltyNumerator; refundPenaltyDenominator = _refundPenaltyDenominator; } /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund block.timestamp. * Note that due to the time required to mine a tx, the actual refund amount will be lower * than what the user reads from this call. */ function getCancelAndRefundValueFor( address _owner ) external view returns (uint refund) { return _getCancelAndRefundValue(_owner); } /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund now. * @param _owner The owner of the key check the refund value for. */ function _getCancelAndRefundValue( address _owner ) private view hasValidKey(_owner) returns (uint refund) { Key storage key = _getKeyFor(_owner); // Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining >= expirationDuration) { refund = keyPrice; } else { // Math: using safeMul in case keyPrice or timeRemaining is very large refund = keyPrice.mul(timeRemaining) / expirationDuration; } uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator; if (refund > penalty) { // Math: safeSub is not required since the if confirms this won't underflow refund -= penalty; } else { refund = 0; } } }
CancelAndRefund will return funds based on time remaining minus this penalty. This is calculated as `proRatedRefund refundPenaltyNumerator / refundPenaltyDenominator`.
{ using SafeMath for uint; uint public refundPenaltyNumerator = 1; uint public refundPenaltyDenominator = 10; event CancelKey( uint indexed tokenId, address indexed owner, uint refund ); event RefundPenaltyChanged( uint oldRefundPenaltyNumerator, uint oldRefundPenaltyDenominator, uint refundPenaltyNumerator, uint refundPenaltyDenominator ); function cancelAndRefund() external { Key storage key = _getKeyFor(msg.sender); uint refund = _getCancelAndRefundValue(msg.sender); emit CancelKey(key.tokenId, msg.sender, refund); key.expirationTimestamp = block.timestamp; if (refund > 0) { _transfer(msg.sender, refund); } } { Key storage key = _getKeyFor(msg.sender); uint refund = _getCancelAndRefundValue(msg.sender); emit CancelKey(key.tokenId, msg.sender, refund); key.expirationTimestamp = block.timestamp; if (refund > 0) { _transfer(msg.sender, refund); } } function updateRefundPenalty( uint _refundPenaltyNumerator, uint _refundPenaltyDenominator ) external onlyOwner { require(_refundPenaltyDenominator != 0, 'INVALID_RATE'); emit RefundPenaltyChanged( refundPenaltyNumerator, refundPenaltyDenominator, _refundPenaltyNumerator, _refundPenaltyDenominator ); refundPenaltyNumerator = _refundPenaltyNumerator; refundPenaltyDenominator = _refundPenaltyDenominator; } function getCancelAndRefundValueFor( address _owner ) external view returns (uint refund) { return _getCancelAndRefundValue(_owner); } function _getCancelAndRefundValue( address _owner ) private view hasValidKey(_owner) returns (uint refund) { Key storage key = _getKeyFor(_owner); uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining >= expirationDuration) { refund = keyPrice; refund = keyPrice.mul(timeRemaining) / expirationDuration; } uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator; if (refund > penalty) { refund -= penalty; refund = 0; } } function _getCancelAndRefundValue( address _owner ) private view hasValidKey(_owner) returns (uint refund) { Key storage key = _getKeyFor(_owner); uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining >= expirationDuration) { refund = keyPrice; refund = keyPrice.mul(timeRemaining) / expirationDuration; } uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator; if (refund > penalty) { refund -= penalty; refund = 0; } } } else { function _getCancelAndRefundValue( address _owner ) private view hasValidKey(_owner) returns (uint refund) { Key storage key = _getKeyFor(_owner); uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining >= expirationDuration) { refund = keyPrice; refund = keyPrice.mul(timeRemaining) / expirationDuration; } uint penalty = keyPrice.mul(refundPenaltyNumerator) / refundPenaltyDenominator; if (refund > penalty) { refund -= penalty; refund = 0; } } } else { }
1,761,061
./full_match/9001/0x9142f0e8dA6C6798b207536567B883269bf0A9E3/sources/contracts/StarFarmLib.sol
Harvest execution method
function harvest(uint256 _pid, address _user, uint256 _amount, bool isNFT) external onlyStarFarm { PoolInfo storage pool = poolInfo[_pid]; UserInfo memory user; SlotInfo memory slot; (user.amount, user.rewardDebt, user.lastDeposit, user.nftAmount, user.nftRewardDebt, ) = starFarm.userInfo(_pid, _user); (slot._selfGain, slot._parentGain) = starNode.nodeGain(_user); uint256 pending; uint256 xPending; slot._self_parentGain = slot._selfGain.add(slot._parentGain); if(isNFT == false){ slot._amountGain = user.amount.add(user.amount.mul(slot._self_parentGain).div(100)); pending = slot._amountGain.mul(pool.accStarPerShare).div(1e22).sub(user.rewardDebt); slot._amountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100)); pending = slot._amountGain.mul(pool.accStarPerShare).div(1e22).sub(user.nftRewardDebt); } if(pool.xRate > 0){ xPending = pending.mul(pool.xRate).div(10000); pending = pending.sub(xPending); } if(pending > 0 || xPending > 0) { if(pending > 0){ iToken.farmMint(address(this), pending); starToken.safeTransfer(alloc.lockAddr,pending.mul(alloc.lockRatio).div(10000)); starToken.safeTransfer(alloc.teamAddr,pending.mul(alloc.teamRatio).div(10000)); pending = pending.sub(pending.mul(alloc.lockRatio.add(alloc.teamRatio)).div(10000)); starToken.safeTransfer(alloc.rewardAddr,pending.mul(alloc.rewardRatio).div(10000)); pending = pending.sub(pending.mul(alloc.rewardRatio).div(10000)); pending = pending.mul(100).div(slot._self_parentGain.add(100)); } if(xPending > 0){ iToken.farmMint(address(this), xPending); IXToken(pool.xToken).farmConvert(alloc.lockAddr,xPending.mul(alloc.lockRatio).div(10000)); IXToken(pool.xToken).farmConvert(alloc.teamAddr,xPending.mul(alloc.teamRatio).div(10000)); xPending = xPending.sub(xPending.mul(alloc.lockRatio.add(alloc.teamRatio)).div(10000)); IXToken(pool.xToken).farmConvert(alloc.rewardAddr,xPending.mul(alloc.rewardRatio).div(10000)); xPending = xPending.sub(xPending.mul(alloc.rewardRatio).div(10000)); xPending = xPending.mul(100).div(slot._self_parentGain.add(100)); } if (user.lastDeposit > block.timestamp.sub(2592000) && isNFT == false) { slot.fee = pending.mul(pool.fee).div(10000); slot.xfee = xPending.mul(pool.fee).div(10000); slot.withdrawAmount = (pending.sub(slot.fee)).mul(slot._selfGain.add(100)).div(100); slot.xwithdrawAmount = (xPending.sub(slot.xfee)).mul(slot._selfGain.add(100)).div(100); starToken.safeTransfer(_user, (pending.sub(slot.fee))); xPending = xPending.sub(xPending.mul(pool.fee).div(10000)); if(xPending>0)IXToken(pool.xToken).farmConvert(_user, xPending); if(slot._self_parentGain > 0){ starToken.safeTransfer(address(starNode), (pending.sub(slot.fee).mul(slot._self_parentGain).div(100))); if(xPending>0)IXToken(pool.xToken).farmConvert(address(starNode), xPending.sub(slot.xfee).mul(slot._self_parentGain).div(100)); starNode.settleNode(_user, (pending.sub(slot.fee).mul(slot._parentGain).div(100)), (pending.sub(slot.fee).mul(slot._selfGain).div(100)), (xPending.sub(slot.fee).mul(slot._parentGain).div(100)), (xPending.sub(slot.fee).mul(slot._selfGain).div(100))); } if(pool.fee > 0){ IBonus Bonus = IBonus(bonusAddr); slot.fee = slot.fee.add(slot.fee.mul(slot._self_parentGain).div(100)); slot.xfee = slot.xfee.add(slot.xfee.mul(slot._self_parentGain).div(100)); starToken.safeTransfer(alloc.lockAddr, slot.fee.mul(Bonus.getlockRatio()).div(100)); slot.amountBonus = slot.fee.sub(slot.fee.mul(Bonus.getlockRatio()).div(100)); slot.xamountBonus = slot.xfee.sub(slot.xfee.mul(Bonus.getlockRatio()).div(100)); starToken.safeTransfer(bonusAddr, slot.amountBonus); if(xPending>0)IXToken(pool.xToken).farmConvert(bonusAddr, slot.xamountBonus); Bonus.addTotalAmount(slot.amountBonus); } slot.withdrawAmount = pending; slot.xwithdrawAmount = xPending; starToken.safeTransfer(_user, pending); if(xPending>0)IXToken(pool.xToken).farmConvert(_user, xPending); if(slot._self_parentGain > 0){ starToken.safeTransfer(address(starNode), pending.mul(slot._self_parentGain).div(100)); if(xPending>0)IXToken(pool.xToken).farmConvert(address(starNode), xPending.mul(slot._self_parentGain).div(100)); } starNode.settleNode(_user, pending.mul(slot._parentGain).div(100), pending.mul(slot._selfGain).div(100), xPending.mul(slot._parentGain).div(100), xPending.mul(slot._selfGain).div(100)); } emit Withdraw(_user, _pid, slot.withdrawAmount, slot.xwithdrawAmount, starFarm.isNodeUser(_user), _amount); } }
11,534,106
/* Utility functions for safe math operations. See link below for more information: https://ethereum.stackexchange.com/questions/15258/safemath-safe-add-function-assertions-against-overflows */ pragma solidity ^0.4.19; contract SafeMath { function safeAdd(uint256 x, uint256 y) pure internal returns (uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) pure internal returns (uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) pure internal returns (uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } function safeDiv(uint256 a, uint256 b) pure internal returns (uint256) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } } contract Owner { // Token Name string public name = "FoodCoin"; // Token Symbol string public symbol = "FOOD"; // Decimals uint256 public decimals = 8; // Version string public version = "v1"; // Emission Address address public emissionAddress = address(0); // Withdraw address address public withdrawAddress = address(0); // Owners Addresses mapping ( address => bool ) public ownerAddressMap; // Owner Address/Number mapping ( address => uint256 ) public ownerAddressNumberMap; // Owners List mapping ( uint256 => address ) public ownerListMap; // Amount of owners uint256 public ownerCountInt = 0; // Modifier - Owner modifier isOwner { require( ownerAddressMap[msg.sender]==true ); _; } // Owner Creation/Activation function ownerOn( address _onOwnerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onOwnerAddress != address(0) ); // If the owner is already exist if ( ownerAddressNumberMap[ _onOwnerAddress ]>0 ) { // If the owner is disablead, activate him again if ( !ownerAddressMap[ _onOwnerAddress ] ) { ownerAddressMap[ _onOwnerAddress ] = true; retrnVal = true; } else { retrnVal = false; } } // If the owner is not exist else { ownerAddressMap[ _onOwnerAddress ] = true; ownerAddressNumberMap[ _onOwnerAddress ] = ownerCountInt; ownerListMap[ ownerCountInt ] = _onOwnerAddress; ownerCountInt++; retrnVal = true; } } // Owner disabled function ownerOff( address _offOwnerAddress ) external isOwner returns (bool retrnVal) { // If owner exist and he is not 0 and active // 0 owner can`t be off if ( ownerAddressNumberMap[ _offOwnerAddress ]>0 && ownerAddressMap[ _offOwnerAddress ] ) { ownerAddressMap[ _offOwnerAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Token name changing function function contractNameUpdate( string _newName, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { name = _newName; retrnVal = true; } else { retrnVal = false; } } // Token symbol changing function function contractSymbolUpdate( string _newSymbol, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { symbol = _newSymbol; retrnVal = true; } else { retrnVal = false; } } // Token decimals changing function function contractDecimalsUpdate( uint256 _newDecimals, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation && _newDecimals != decimals ) { decimals = _newDecimals; retrnVal = true; } else { retrnVal = false; } } // New token emission address setting up function emissionAddressUpdate( address _newEmissionAddress ) external isOwner { emissionAddress = _newEmissionAddress; } // New token withdrawing address setting up function withdrawAddressUpdate( address _newWithdrawAddress ) external isOwner { withdrawAddress = _newWithdrawAddress; } // Constructor adds owner to undeletable list function Owner() public { // Owner creation ownerAddressMap[ msg.sender ] = true; ownerAddressNumberMap[ msg.sender ] = ownerCountInt; ownerListMap[ ownerCountInt ] = msg.sender; ownerCountInt++; } } contract SpecialManager is Owner { // Special Managers Addresses mapping ( address => bool ) public specialManagerAddressMap; // Special Manager Address/Number Mapping mapping ( address => uint256 ) public specialManagerAddressNumberMap; // Special Managers List mapping ( uint256 => address ) public specialManagerListMap; // Special Manager Amount uint256 public specialManagerCountInt = 0; // Special Manager or Owner modifier modifier isSpecialManagerOrOwner { require( specialManagerAddressMap[msg.sender]==true || ownerAddressMap[msg.sender]==true ); _; } // Special Manager creation/actination function specialManagerOn( address _onSpecialManagerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onSpecialManagerAddress != address(0) ); // If this special manager already exists if ( specialManagerAddressNumberMap[ _onSpecialManagerAddress ]>0 ) { // If this special manager disabled, activate him again if ( !specialManagerAddressMap[ _onSpecialManagerAddress ] ) { specialManagerAddressMap[ _onSpecialManagerAddress ] = true; retrnVal = true; } else { retrnVal = false; } } // If this special manager doesn`t exist else { specialManagerAddressMap[ _onSpecialManagerAddress ] = true; specialManagerAddressNumberMap[ _onSpecialManagerAddress ] = specialManagerCountInt; specialManagerListMap[ specialManagerCountInt ] = _onSpecialManagerAddress; specialManagerCountInt++; retrnVal = true; } } // Special manager disactivation function specialManagerOff( address _offSpecialManagerAddress ) external isOwner returns (bool retrnVal) { // If this special manager exists and he is non-zero and also active // 0-number manager can`t be disactivated if ( specialManagerAddressNumberMap[ _offSpecialManagerAddress ]>0 && specialManagerAddressMap[ _offSpecialManagerAddress ] ) { specialManagerAddressMap[ _offSpecialManagerAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Constructor adds owner to superowner list function SpecialManager() public { // owner creation specialManagerAddressMap[ msg.sender ] = true; specialManagerAddressNumberMap[ msg.sender ] = specialManagerCountInt; specialManagerListMap[ specialManagerCountInt ] = msg.sender; specialManagerCountInt++; } } contract Manager is SpecialManager { // Managers addresses mapping ( address => bool ) public managerAddressMap; // Manager Address/Number Mapping mapping ( address => uint256 ) public managerAddressNumberMap; // Managers` List mapping ( uint256 => address ) public managerListMap; // Amount of managers uint256 public managerCountInt = 0; // Modifier - Manager Or Owner modifier isManagerOrOwner { require( managerAddressMap[msg.sender]==true || ownerAddressMap[msg.sender]==true ); _; } // Owner Creation/Activation function managerOn( address _onManagerAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onManagerAddress != address(0) ); // If this special manager exists if ( managerAddressNumberMap[ _onManagerAddress ]>0 ) { // If this special manager disabled, activate him again if ( !managerAddressMap[ _onManagerAddress ] ) { managerAddressMap[ _onManagerAddress ] = true; retrnVal = true; } else { retrnVal = false; } } // If this special manager doesn`t exist else { managerAddressMap[ _onManagerAddress ] = true; managerAddressNumberMap[ _onManagerAddress ] = managerCountInt; managerListMap[ managerCountInt ] = _onManagerAddress; managerCountInt++; retrnVal = true; } } // Manager disactivation function managerOff( address _offManagerAddress ) external isOwner returns (bool retrnVal) { // if it's a non-zero manager and already exists and active // 0-number manager can`t be disactivated if ( managerAddressNumberMap[ _offManagerAddress ]>0 && managerAddressMap[ _offManagerAddress ] ) { managerAddressMap[ _offManagerAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Constructor adds owner to manager list function Manager() public { // manager creation managerAddressMap[ msg.sender ] = true; managerAddressNumberMap[ msg.sender ] = managerCountInt; managerListMap[ managerCountInt ] = msg.sender; managerCountInt++; } } contract Management is Manager { // Description string public description = ""; // Current tansaction status // TRUE - tansaction available // FALSE - tansaction not available bool public transactionsOn = false; // Special permissions to allow/prohibit transactions to move tokens for specific accounts // 0 - depends on transactionsOn // 1 - always "forbidden" // 2 - always "allowed" mapping ( address => uint256 ) public transactionsOnForHolder; // Displaying tokens in the balanceOf function for all tokens // TRUE - Displaying available // FALSE - Displaying hidden, shows 0. Checking the token balance available in function balanceOfReal bool public balanceOfOn = true; // Displaying the token balance in function balanceOfReal for definit holder // 0 - depends on transactionsOn // 1 - always "forbidden" // 2 - always "allowed" mapping ( address => uint256 ) public balanceOfOnForHolder; // Current emission status // TRUE - emission is available, managers may add tokens to contract // FALSE - emission isn`t available, managers may not add tokens to contract bool public emissionOn = true; // emission cap uint256 public tokenCreationCap = 0; // Addresses list for verification of acoounts owners // Addresses mapping ( address => bool ) public verificationAddressMap; // Verification Address/Number Mapping mapping ( address => uint256 ) public verificationAddressNumberMap; // Verification List Mapping mapping ( uint256 => address ) public verificationListMap; // Amount of verifications uint256 public verificationCountInt = 1; // Verification holding // Verification Holders Timestamp mapping (address => uint256) public verificationHoldersTimestampMap; // Verification Holders Value mapping (address => uint256) public verificationHoldersValueMap; // Verification Holders Verifier Address mapping (address => address) public verificationHoldersVerifierAddressMap; // Verification Address Holders List Count mapping (address => uint256) public verificationAddressHoldersListCountMap; // Verification Address Holders List Number mapping (address => mapping ( uint256 => address )) public verificationAddressHoldersListNumberMap; // Modifier - Transactions On modifier isTransactionsOn( address addressFrom ) { require( transactionsOnNowVal( addressFrom ) ); _; } // Modifier - Emission On modifier isEmissionOn{ require( emissionOn ); _; } // Function transactions On now validate for definit address function transactionsOnNowVal( address addressFrom ) public view returns( bool ) { return ( transactionsOnForHolder[ addressFrom ]==0 && transactionsOn ) || transactionsOnForHolder[ addressFrom ]==2 ; } // transaction allow/forbidden for definit token holder function transactionsOnForHolderUpdate( address _to, uint256 _newValue ) external isOwner { if ( transactionsOnForHolder[ _to ] != _newValue ) { transactionsOnForHolder[ _to ] = _newValue; } } // Function of changing allow/forbidden transfer status function transactionsStatusUpdate( bool _on ) external isOwner { transactionsOn = _on; } // Function of changing emission status function emissionStatusUpdate( bool _on ) external isOwner { emissionOn = _on; } // Emission cap setting up function tokenCreationCapUpdate( uint256 _newVal ) external isOwner { tokenCreationCap = _newVal; } // balanceOfOnForHolder; balanceOfOn // Function on/off token displaying in function balanceOf function balanceOfOnUpdate( bool _on ) external isOwner { balanceOfOn = _on; } // Function on/off token displaying in function balanceOf for definit token holder function balanceOfOnForHolderUpdate( address _to, uint256 _newValue ) external isOwner { if ( balanceOfOnForHolder[ _to ] != _newValue ) { balanceOfOnForHolder[ _to ] = _newValue; } } // Function adding of new verification address function verificationAddressOn( address _onVerificationAddress ) external isOwner returns (bool retrnVal) { // Check if it's a non-zero address require( _onVerificationAddress != address(0) ); // If this address is already exists if ( verificationAddressNumberMap[ _onVerificationAddress ]>0 ) { // If address off, activate it again if ( !verificationAddressMap[ _onVerificationAddress ] ) { verificationAddressMap[ _onVerificationAddress ] = true; retrnVal = true; } else { retrnVal = false; } } // If this address doesn`t exist else { verificationAddressMap[ _onVerificationAddress ] = true; verificationAddressNumberMap[ _onVerificationAddress ] = verificationCountInt; verificationListMap[ verificationCountInt ] = _onVerificationAddress; verificationCountInt++; retrnVal = true; } } // Function of disactivation of verification address function verificationOff( address _offVerificationAddress ) external isOwner returns (bool retrnVal) { // If this verification address exists and disabled if ( verificationAddressNumberMap[ _offVerificationAddress ]>0 && verificationAddressMap[ _offVerificationAddress ] ) { verificationAddressMap[ _offVerificationAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Event "Description updated" event DescriptionPublished( string _description, address _initiator); // Description update function descriptionUpdate( string _newVal ) external isOwner { description = _newVal; DescriptionPublished( _newVal, msg.sender ); } } // Token contract FoodCoin Ecosystem contract FoodcoinEcosystem is SafeMath, Management { // Token total supply uint256 public totalSupply = 0; // Balance mapping ( address => uint256 ) balances; // Balances List Address mapping ( uint256 => address ) public balancesListAddressMap; // Balances List/Number Mapping mapping ( address => uint256 ) public balancesListNumberMap; // Balances Address Description mapping ( address => string ) public balancesAddressDescription; // Total amount of all balances uint256 balancesCountInt = 1; // Forwarding of address managing for definit amount of tokens mapping ( address => mapping ( address => uint256 ) ) allowed; // Standard ERC-20 events // Event - token transfer event Transfer( address indexed from, address indexed to, uint value ); // Event - Forwarding of address managing event Approval( address indexed owner, address indexed spender, uint value ); // Token transfer event FoodTransferEvent( address from, address to, uint256 value, address initiator, uint256 newBalanceFrom, uint256 newBalanceTo ); // Event - Emission event FoodTokenEmissionEvent( address initiator, address to, uint256 value, bool result, uint256 newBalanceTo ); // Event - Withdraw event FoodWithdrawEvent( address initiator, address to, bool withdrawOk, uint256 withdraw, uint256 withdrawReal, uint256 newBalancesValue ); // Balance View function balanceOf( address _owner ) external view returns ( uint256 ) { // If allows to display balance for all or definit holder if ( ( balanceOfOnForHolder[ _owner ]==0 && balanceOfOn ) || balanceOfOnForHolder[ _owner ]==2 ) { return balances[ _owner ]; } else { return 0; } } // Real Balance View function balanceOfReal( address _owner ) external view returns ( uint256 ) { return balances[ _owner ]; } // Check if a given user has been delegated rights to perform transfers on behalf of the account owner function allowance( address _owner, address _initiator ) external view returns ( uint256 remaining ) { return allowed[ _owner ][ _initiator ]; } // Total balances quantity function balancesQuantity() external view returns ( uint256 ) { return balancesCountInt - 1; } // Function of token transaction. For the first transaction will be created the detailed information function _addClientAddress( address _balancesAddress, uint256 _amount ) internal { // check if this address is not on the list yet if ( balancesListNumberMap[ _balancesAddress ] == 0 ) { // add it to the list balancesListAddressMap[ balancesCountInt ] = _balancesAddress; balancesListNumberMap[ _balancesAddress ] = balancesCountInt; // increment account counter balancesCountInt++; } // add tokens to the account balances[ _balancesAddress ] = safeAdd( balances[ _balancesAddress ], _amount ); } // Internal function that performs the actual transfer (cannot be called externally) function _transfer( address _from, address _to, uint256 _value ) internal isTransactionsOn( _from ) returns ( bool success ) { // If the amount to transfer is greater than 0, and sender has funds available if ( _value > 0 && balances[ _from ] >= _value ) { // Subtract from sender account balances[ _from ] -= _value; // Add to receiver's account _addClientAddress( _to, _value ); // Perform the transfer Transfer( _from, _to, _value ); FoodTransferEvent( _from, _to, _value, msg.sender, balances[ _from ], balances[ _to ] ); // Successfully completed transfer return true; } // Return false if there are problems else { return false; } } // Function token transfer function transfer(address _to, uint256 _value) external returns ( bool success ) { // If it is transfer to verification address if ( verificationAddressNumberMap[ _to ]>0 ) { _verification(msg.sender, _to, _value); } // Regular transfer else { // Call function transfer. return _transfer( msg.sender, _to, _value ); } } // Function of transferring tokens from a delegated account function transferFrom(address _from, address _to, uint256 _value) external isTransactionsOn( _from ) returns ( bool success ) { // Regular transfer. Not to verification address require( verificationAddressNumberMap[ _to ]==0 ); // Check if the transfer initiator has permissions to move funds from the sender's account if ( allowed[_from][msg.sender] >= _value ) { // If yes - perform transfer if ( _transfer( _from, _to, _value ) ) { // Decrease the total amount that initiator has permissions to access allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender], _value); return true; } else { return false; } } else { return false; } } // Function of delegating account management for a certain amount function approve( address _initiator, uint256 _value ) external isTransactionsOn( msg.sender ) returns ( bool success ) { // Grant the rights for a certain amount of tokens only allowed[ msg.sender ][ _initiator ] = _value; // Initiate the Approval event Approval( msg.sender, _initiator, _value ); return true; } // The emission function (the manager or contract owner creates tokens and sends them to a specific account) function _emission (address _reciever, uint256 _amount) internal isManagerOrOwner isEmissionOn returns ( bool returnVal ) { // if non-zero address if ( _reciever != address(0) ) { // Calculate number of tokens after generation uint256 checkedSupply = safeAdd( totalSupply, _amount ); // Emission amount uint256 amountTmp = _amount; // If emission cap settled additional emission is impossible if ( tokenCreationCap > 0 && tokenCreationCap < checkedSupply ) { amountTmp = 0; } // if try to add more than 0 tokens if ( amountTmp > 0 ) { // If no error, add generated tokens to a given address _addClientAddress( _reciever, amountTmp ); // increase total supply of tokens totalSupply = checkedSupply; // event "token transfer" Transfer( emissionAddress, _reciever, amountTmp ); // event "emission successfull" FoodTokenEmissionEvent( msg.sender, _reciever, _amount, true, balances[ _reciever ] ); } else { returnVal = false; // event "emission failed" FoodTokenEmissionEvent( msg.sender, _reciever, _amount, false, balances[ _reciever ] ); } } } // emission to definit 1 address function tokenEmission(address _reciever, uint256 _amount) external isManagerOrOwner isEmissionOn returns ( bool returnVal ) { // Check if it's a non-zero address require( _reciever != address(0) ); // emission in process returnVal = _emission( _reciever, _amount ); } // adding 5 addresses at once function tokenEmission5( address _reciever_0, uint256 _amount_0, address _reciever_1, uint256 _amount_1, address _reciever_2, uint256 _amount_2, address _reciever_3, uint256 _amount_3, address _reciever_4, uint256 _amount_4 ) external isManagerOrOwner isEmissionOn { _emission( _reciever_0, _amount_0 ); _emission( _reciever_1, _amount_1 ); _emission( _reciever_2, _amount_2 ); _emission( _reciever_3, _amount_3 ); _emission( _reciever_4, _amount_4 ); } // Function Tokens withdraw function withdraw( address _to, uint256 _amount ) external isSpecialManagerOrOwner returns ( bool returnVal, uint256 withdrawValue, uint256 newBalancesValue ) { // check if this is a valid account if ( balances[ _to ] > 0 ) { // Withdraw amount uint256 amountTmp = _amount; // It is impossible to withdraw more than available on balance if ( balances[ _to ] < _amount ) { amountTmp = balances[ _to ]; } // Withdraw in process balances[ _to ] = safeSubtract( balances[ _to ], amountTmp ); // Changing of current tokens amount totalSupply = safeSubtract( totalSupply, amountTmp ); // Return reply returnVal = true; withdrawValue = amountTmp; newBalancesValue = balances[ _to ]; FoodWithdrawEvent( msg.sender, _to, true, _amount, amountTmp, balances[ _to ] ); // Event "Token transfer" Transfer( _to, withdrawAddress, amountTmp ); } else { returnVal = false; withdrawValue = 0; newBalancesValue = 0; FoodWithdrawEvent( msg.sender, _to, false, _amount, 0, balances[ _to ] ); } } // Balance description update function balancesAddressDescriptionUpdate( string _newDescription ) external returns ( bool returnVal ) { // If this address or contrat`s owher exists if ( balancesListNumberMap[ msg.sender ] > 0 || ownerAddressMap[msg.sender]==true ) { balancesAddressDescription[ msg.sender ] = _newDescription; returnVal = true; } else { returnVal = false; } } // Recording of verification details function _verification( address _from, address _verificationAddress, uint256 _value) internal { // If verification address is active require( verificationAddressMap[ _verificationAddress ] ); // If it is updating of already verificated address if ( verificationHoldersVerifierAddressMap[ _from ] == _verificationAddress ) { // Verification Address Holders List Count uint256 tmpNumberVerification = verificationAddressHoldersListCountMap[ _verificationAddress ]; verificationAddressHoldersListCountMap[ _verificationAddress ]++; // Verification Address Holders List Number verificationAddressHoldersListNumberMap[ _verificationAddress ][ tmpNumberVerification ] = _from; } // Verification Holders Timestamp verificationHoldersTimestampMap[ _from ] = now; // Verification Value verificationHoldersValueMap[ _from ] = _value; // Verification Holders Verifier Address verificationHoldersVerifierAddressMap[ _from ] = _verificationAddress; } }
Function of transferring tokens from a delegated account Regular transfer. Not to verification address Check if the transfer initiator has permissions to move funds from the sender's account If yes - perform transfer Decrease the total amount that initiator has permissions to access
function transferFrom(address _from, address _to, uint256 _value) external isTransactionsOn( _from ) returns ( bool success ) { require( verificationAddressNumberMap[ _to ]==0 ); if ( allowed[_from][msg.sender] >= _value ) { if ( _transfer( _from, _to, _value ) ) { allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender], _value); return true; } else { return false; } } else { return false; } }
6,396,232
pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import { ContractUpgradeableSigner } from './contract-upgradeable-signer.sol'; import { DataStructures } from './data-structures.sol'; contract Network is ContractUpgradeableSigner { uint constant public maxTransfersInProgress = 10; uint constant public transferTimeBlocks = 100; constructor () ContractUpgradeableSigner(msg.sender) public { } uint public transfersInProgress; mapping (bytes32 => DataStructures.Status) public transfers; uint constant public remedyTimeoutBlocks = 100; uint constant public maxTransfer = 1000; uint constant public minTransfer = 1; uint constant public feeNumber = 1; uint constant public feeBasisPoints = 10; address constant public recoverableTokenContract = address(0x0); modifier onlyLinkedRecoverableTokenContract { require(msg.sender == recoverableTokenContract, "Only Linked Recoverable Token Contract May Call This"); _; } // getTransfer returns the transfer from the transfers mapping function getTransfer( bytes32 checkHash ) public view returns (DataStructures.Status memory) { return transfers[checkHash]; } // isAcceptableTransfer checks to see if this transfer may submitted to the network function isAcceptableTransfer( DataStructures.Quote memory quote ) public view returns (bool) { if(quote.blockNumberMin > block.number){ return false; } if(quote.blockNumberMax < block.number && quote.blockNumberMax != 0){ return false; } if(maxTransfersInProgress > transfersInProgress + 1){ return false; } if(maxTransfer < quote.amount){ return false; } if(minTransfer > quote.amount){ return false; } return true; } // getFee returns the fee based on sending an amount on the given network function getFee( uint amount ) public pure returns (uint predictedFee) { predictedFee = (amount * feeBasisPoints / 10000) + feeNumber; return predictedFee; } // post transfer adds a transfer to the network function postTransfer( bytes32 hashedCheck ) public onlyLinkedRecoverableTokenContract returns (bool) { require(maxTransfersInProgress > transfersInProgress, "Too many transfer in progress"); require(transfers[hashedCheck].blockStarted == 0, "Transfer aleady started"); transfers[hashedCheck].blockStarted = block.number; ++transfers[hashedCheck].nonce; ++transfersInProgress; return true; } // update the transfer status function updateTransferStatus( bytes32 hashedCheck, DataStructures.TransferState updatedState ) public onlyLinkedRecoverableTokenContract returns (bool) { if(updatedState == DataStructures.TransferState.Closed){ --transfersInProgress; delete transfers[hashedCheck]; return true; } ++transfers[hashedCheck].nonce; transfers[hashedCheck].state = updatedState; return false; } // closeNetwork() function notify( address, // _from, address, // _to, uint, // amount, bool // isRemedy ) public onlyLinkedRecoverableTokenContract returns (bool) { return true; } }
isAcceptableTransfer checks to see if this transfer may submitted to the network
function isAcceptableTransfer( DataStructures.Quote memory quote ) public view returns (bool) { if(quote.blockNumberMin > block.number){ return false; } if(quote.blockNumberMax < block.number && quote.blockNumberMax != 0){ return false; } if(maxTransfersInProgress > transfersInProgress + 1){ return false; } if(maxTransfer < quote.amount){ return false; } if(minTransfer > quote.amount){ return false; } return true; }
14,104,368
pragma solidity >0.8.0; import "./FlightSuretyData.sol"; import "./FlightSuretyGovernance.sol"; import "./FlightSuretyWallet.sol"; //solidity >0.8.x integrates safe math /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ FlightSuretyData private dataContract; FlightSuretyGovernance private governanceContract; FlightSuretyWalletFactory private walletFactory; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; bool private initialized = false; // Fees uint private constant USER_REGISTRATION_FEE = 2 gwei; uint private constant INSURANCE_FEE = 1 gwei; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; event log(); event changedDataContract( address newAddress); event changedGovernanceContract( address newAddress); event changedWalletContract( address newAddress); event insuranceBought(address user, uint amount, bytes32 flightKey, address airline); /********************************************************************************************/ /* 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() { // Modify to call data contract's status require(true, "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"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( ) { contractOwner = msg.sender; } function init(address _dataContract, address _governanceContract, address _walletFactory, address firstAirlineAddress ) public requireContractOwner {require(!initialized); setDataContract(_dataContract); setGovernanceContract(_governanceContract); setWalletFactory(_walletFactory); initialized = true; dataContract.init(firstAirlineAddress, walletFactory.createAirlineWallet(firstAirlineAddress)); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return dataContract.isOperational(); // Modify to call data contract's status } function setOperatingStatus(bool mode) public returns(bool,uint){ bool isAirline = dataContract.isRegisteredAirline(msg.sender) ; bool isOwner = contractOwner == msg.sender; require (isAirline || isOwner , "Unauthorized"); if (isAirline){ governanceContract.voteChangeOperationalState(msg.sender); (bool result, uint256 votes) = governanceContract .getResult(dataContract .getCounter()); if (result) { dataContract.setOperatingStatus(mode); } return (result, votes); } else { dataContract.setOperatingStatus(mode); return(true, 0); } } function setDataContract(address _dataContract) public requireContractOwner{ dataContract = FlightSuretyData(payable(_dataContract)); emit changedDataContract(_dataContract); } function setGovernanceContract(address _governanceContract) public requireContractOwner{ governanceContract = FlightSuretyGovernance(_governanceContract); emit changedGovernanceContract(_governanceContract); } function setWalletFactory(address _walletFactory) public requireContractOwner { walletFactory = FlightSuretyWalletFactory(_walletFactory); emit changedWalletContract(_walletFactory); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline ( address airline ) external returns(bool success, uint256 _votes) { require((!dataContract.isRegisteredAirline(airline) && dataContract.isRegisteredAirline(msg.sender) && dataContract.getAirlineWallet(msg.sender).getBalance() >= 10 ether) || msg.sender == contractOwner ); emit log(); //casts vote on governance contract, then checks result governanceContract.vote(airline, msg.sender); (bool result, uint256 votes) = governanceContract .getResult(dataContract .getCounter()); if (result){ //if vote passed, register new airline with corresponding wallet in data contract airlineWallet wallet = walletFactory.createAirlineWallet(msg.sender); dataContract.addAirline(airline, wallet); } return (result, votes); } /** * @dev Register a future flight for insuring. * */ function registerFlight (string memory _flight ) external returns(bytes32) { //check that msg.sender is registered airline with more than 10 funds deposited myWallet wallet = dataContract.getAirlineWallet(msg.sender); require(dataContract.isRegisteredAirline(msg.sender) && wallet.getBalance() >= 10); bytes32 key = getFlightKey(msg.sender, _flight , block.timestamp); Flight memory flight = flights[key]; flight.isRegistered = true; flight.statusCode = STATUS_CODE_UNKNOWN; flight.updatedTimestamp = block.timestamp; flight.airline = msg.sender; flights[key] = flight; return key; } function _getFlightKey(uint256 flightNo) private pure returns(bytes32){ return keccak256(abi.encode(flightNo)); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( address airline, string memory _flight, uint256 timestamp, uint8 statusCode ) internal { bytes32 key = getFlightKey(airline, _flight, timestamp); Flight storage flight = flights[key]; require(flight.isRegistered); flight.statusCode = statusCode; flight.updatedTimestamp = timestamp; flights[key] = flight; } /** * @dev Register new user */ function registerUser() external payable{ require(!dataContract.isRegisteredUser(msg.sender), "user already registered"); require(msg.value > USER_REGISTRATION_FEE); userWallet wallet = walletFactory.createUserWallet(msg.sender); payable(address(wallet)).transfer(msg.value - USER_REGISTRATION_FEE); dataContract.addUser(msg.sender, wallet); _fundDataContract(msg.value - USER_REGISTRATION_FEE); } /** * @dev Buy insurance for a flight * */ function buy (bytes32 flightKey) external payable { require(dataContract.isRegisteredUser(msg.sender), "user not registered"); require((1 ether >= msg.value) && (msg.value > INSURANCE_FEE)); userWallet wallet = dataContract.getUserWallet(msg.sender); payable(address(wallet)).transfer(msg.value - INSURANCE_FEE); wallet.insure(msg.value - INSURANCE_FEE, flightKey); Flight memory flight = flights[flightKey]; address airline = flight.airline; dataContract .getAirlineWallet(airline) .addInsuree(msg.sender, flightKey); _fundDataContract(msg.value - INSURANCE_FEE); emit insuranceBought(msg.sender, msg.value, flightKey, airline); } /** * @dev Credits payouts to insurees */ function creditInsurees (bytes32 flightKey ) internal { Flight memory flight = flights[flightKey]; require(flight.statusCode == STATUS_CODE_LATE_AIRLINE); address airline = flight.airline; airlineWallet Awallet = dataContract.getAirlineWallet(airline); address[] memory insurees = Awallet.getInsurees(flightKey); uint256 paidOut = 0; for(uint i=0; i< insurees.length; i++){ userWallet Uwallet = dataContract.getUserWallet(insurees[i]); uint256 amount = Uwallet.getInsuredFlight(flightKey) / 2 * 3; payable(address(Uwallet)).transfer(amount); paidOut += amount; Uwallet.clear(flightKey); } Awallet.withdraw(paidOut); Awallet.clear(flightKey); } function payOut(bytes32 flightKey) external returns (uint){ creditInsurees(flightKey); return dataContract.pay(msg.sender); } function _fundDataContract(uint256 amount) private{ address dataAddress = address(dataContract); payable(dataAddress).transfer(amount); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string memory flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key].requester = msg.sender; oracleResponses[key].isOpen = true; emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); event OracleRegistered(address oracle); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); Oracle storage thisOracle = oracles[msg.sender]; thisOracle.isRegistered = true; thisOracle.indexes = indexes; oracles[msg.sender] = thisOracle; emit OracleRegistered(msg.sender); } function getMyIndexes ( ) view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Called by oracle when a response is available to an outstanding request For the response to be accepted, there must be a pending request that is open and matches one of the three Indexes randomly assigned to the oracle at the time of registration (i.e. uninvited oracles are not welcome) Information isn't considered verified until at least MIN_RESPONSES oracles respond with the same information Handle flight status as appropriate
function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); processFlightStatus(airline, flight, timestamp, statusCode); } }
2,545,735
./partial_match/1/0xD034b96388C2919c0a1BdcAC5ad34c3e5F8a99EA/sources/ERC20ByMetadropV1.sol
function {_autoSwap} Automate the swap of accumulated tax fees to native token from_ The sender of the token/ Store that a swap back is in progress: Perform the auto swap to native token: Flag that the autoswap is complete:
function _autoSwap(address from_, address to_) internal { if (tokenHasTax) { uint256 taxBalance = balanceOf(address(this)); if (_eligibleForSwap(from_, to_, taxBalance)) { autoSwapEnabled = false; _swapTaxForNative(taxBalance); autoSwapEnabled = true; } } }
4,221,087
./full_match/8453/0x7D691e6b03b46B5A5769299fC9a32EaC690B7abc/sources/contracts/libraries/Locations.sol
Decodes the lower bytes of a location as an address. This assumes location type is an address. loc The location to convert. return addr The location as an address./
function locationToAddress(bytes32 loc) internal pure returns (address addr) { bytes32 lower31 = loc & MASK_POOL_ID; if(lower31 > MASK_ADDRESS) revert Errors.HydrogenInvalidLocationToAddressCast(); return address(uint160(uint256(lower31))); }
11,557,815
./partial_match/1/0x52dAb11c6029862eBF1E65A4d5c30641f5FbD957/sources/AccountLogic.sol
called from 'enter'
function changeAllOperationKeys(address payable _account, address[] calldata _pks) external allowSelfCallsOnly { uint256 keyCount = accountStorage.getOperationKeyCount(_account); require(_pks.length == keyCount, "invalid number of keys"); require(accountStorage.getDelayDataHash(_account, CHANGE_ALL_OPERATION_KEYS) == 0, "delay data already exists"); address pk; for (uint256 i = 0; i < keyCount; i++) { pk = _pks[i]; require(pk != address(0), "0x0 is invalid"); } bytes32 hash = keccak256(abi.encodePacked('changeAllOperationKeys', _account, _pks)); accountStorage.setDelayData(_account, CHANGE_ALL_OPERATION_KEYS, hash, now + DELAY_CHANGE_OPERATION_KEY); }
16,014,809
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#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; } } /** * @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 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 SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _wallet Address where collected funds will be forwarded to */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(token != address(0x0)); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit on number of tokens for sale. */ contract CappedTokenCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenCap; uint256 public tokensSold; /** * @dev Constructor, takes maximum amount of tokens to be sold in the crowdsale. * @param _tokenCap Max amount of tokens to be sold */ constructor(uint256 _tokenCap) public { require(_tokenCap > 0); tokenCap = _tokenCap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function tokenCapReached() public view returns (bool) { return tokensSold >= tokenCap; } /** * @dev Extend parent behavior requiring purchase to respect the token cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(!tokenCapReached()); } /** * @dev Overrides parent to increase the number of tokensSold. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { tokensSold = tokensSold.add(_tokenAmount); super._processPurchase(_beneficiary, _tokenAmount); } } /** * @title IncreasingTokenPriceCrowdsale * @dev Extension of Crowdsale contract that increases the price of one token linearly in time. * Note that what should be provided to the constructor is the initial and final _rates_, that is, * the amount of wei per one token. Thus, the initial rate must be less than the final rate. */ contract IncreasingTokenPriceCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public initialRate; uint256 public finalRate; /** * @dev Constructor, takes initial and final rates of wei contributed per token. * @param _initialRate Number of wei it costs for one token at the start of the crowdsale * @param _finalRate Number of wei it costs for one token at the end of the crowdsale */ constructor(uint256 _initialRate, uint256 _finalRate) public { require(_finalRate >= _initialRate); require(_initialRate > 0); initialRate = _initialRate; finalRate = _finalRate; } /** * @dev Returns the rate of wei per token at the present time. * @return The number of wei it costs for one token at a given time */ function getCurrentRate() public view returns (uint256) { // solium-disable-next-line security/no-block-members uint256 elapsedTime = block.timestamp.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = finalRate.sub(initialRate); return initialRate.add(elapsedTime.mul(rateRange).div(timeRange)); } /** * @dev Overrides parent method taking into account variable rate. * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return _weiAmount.div(currentRate); } } /** * @title FOIChainCrowdsale * @dev The FOI crowdsale contract. It inherits from several other crowdsale contracts to provide the required functionality. * The crowdsale runs from 12:00 am GMT, August 13th, to 11:59 pm GMT, October 12th. * The price increases linearly from 0.05 ether per token, to 0.25 ether per token. * A maximum of 200,000 tokens can be purchased. * 50,000 tokens are reserved for the FOIChain organization to fund the on-going development of the web app front end. * Any unsold tokens will go to the FOIChain organization. */ contract FOIChainCrowdsale is TimedCrowdsale, MintedCrowdsale, IncreasingTokenPriceCrowdsale, PostDeliveryCrowdsale, CappedTokenCrowdsale, FinalizableCrowdsale { using SafeMath for uint256; address constant internal walletAddress = 0x870c6bd22325673D28d9a5da465dFef3073AB3E7; uint256 constant internal startOfAugust13 = 1534118400; uint256 constant internal endOfOctober12 = 1539388740; /** * @dev Constructor, creates crowdsale contract with wallet to send funds to, * an opening and closing time, an initialRate and finalRate, and a token cap. */ constructor() public Crowdsale(walletAddress) TimedCrowdsale(startOfAugust13, endOfOctober12) IncreasingTokenPriceCrowdsale(0.05 ether, 0.25 ether) PostDeliveryCrowdsale() CappedTokenCrowdsale(200000) FinalizableCrowdsale() { } /** * @dev Allows the owner to update the address of the to-be-written FOI token contract. * When the pre-sale is over, this contract will mint the tokens for people who purchased * in the pre-sale. * Make sure that this contract is the owner of the token contract. * @param _token The address of the FOI token contract */ function updateTokenAddress(MintableToken _token) onlyOwner public { require(!isFinalized); require(_token.owner() == address(this)); token = _token; } /** * @dev Validate that enough ether was sent to buy at least one token. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei sent to the contract */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 currentRate = getCurrentRate(); uint256 tokenAmount = _weiAmount.div(currentRate); require(tokenAmount > 0); } /** * @dev Public function for getting the number of tokens _weiAmount contributed would purchase. * @param _weiAmount Amount of wei sent to the contract * @return Number of tokens _weiAmount contributed would purchase */ function getTokenAmount(uint256 _weiAmount) public view returns(uint256) { return _getTokenAmount(_weiAmount); } /** * @dev Overrides parent method taking into account the token cap. * @param _weiAmount Amount of wei sent to the contract * @return Number of tokens _weiAmount contributed would purchase */ function _getTokenAmount(uint256 _weiAmount) internal view returns(uint256) { uint256 tokenAmount = super._getTokenAmount(_weiAmount); uint256 unsold = unsoldTokens(); if(tokenAmount > unsold) { tokenAmount = unsold; } return tokenAmount; } /** * @dev Calculates how many tokens have not been sold in the pre-sale * @return Number of tokens that have not been sold in the pre-sale. */ function unsoldTokens() public view returns (uint256) { return tokenCap.sub(tokensSold); } /** * @dev Gets the balance of the specified address. * @param _user The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function getBalance(address _user) public view returns(uint256) { return balances[_user]; } event EtherRefund( address indexed purchaser, uint256 refund ); /** * @dev Overrides parent to calculate how much extra wei was sent, and issues a refund. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { super._processPurchase(_beneficiary, _tokenAmount); uint256 currentRate = getCurrentRate(); uint256 weiSpent = currentRate.mul(_tokenAmount); uint256 weiAmount = msg.value; uint256 refund = weiAmount.sub(weiSpent); if(refund > 0) { weiRaised = weiRaised.sub(refund); msg.sender.transfer(refund); emit EtherRefund( msg.sender, refund ); } } /** * @dev Overrides parent to forward the complete balance to the wallet. * This contract should never contain any ether. */ function _forwardFunds() internal { wallet.transfer(address(this).balance); } /** * @dev Overrides parent to only allow withdraws after the pre-sale has been finalized. */ function withdrawTokens() public { require(isFinalized); super.withdrawTokens(); } /** * @dev Overrides parent to perform custom finalization logic. * After the pre-sale is over, 50,000 tokens will be allocated to the FOI organization * to support the on-going development of the FOI smart contract and web app front end. * Note that any unsold tokens will also be allocated to the FOI organization. */ function finalization() internal { uint256 reserve = 50000; uint256 remaining = tokenCap.sub(tokensSold).add(reserve); balances[wallet] = balances[wallet].add(remaining); super.finalization(); } }
Overrides parent to increase the number of tokensSold. _beneficiary Address receiving the tokens _tokenAmount Number of tokens to be purchased/
function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { tokensSold = tokensSold.add(_tokenAmount); super._processPurchase(_beneficiary, _tokenAmount); }
2,334,225
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; contract Airdrop is Ownable, Pausable { using SafeERC20 for IERC20; /// @notice address of USDC token address public immutable tokenUSDC; /// @notice address of BUMP token address public immutable tokenBUMP; /// @notice Merkle tree root hash /// @dev Should be computed off-chain and be passed to contract /// every time, when data, stored in tree nodes (address and amount of BUMP/USDC) /// changes bytes32 public merkleRoot; /// @notice Packed array of booleans. /// @dev Value should be set using _setClaimed() function /// Value should be taken using isClaimed() function mapping(uint256 => uint256) private claimedBitMap; // This event is triggered whenever a claim succeeds event Claimed( uint256 index, address indexed account, uint256 amountUSDC, uint256 amountBUMP, uint256 timestamp ); /// @param _tokenUSDC USDC token address /// @param _tokenBUMP BUMP token address /// @param _merkleRoot Initial hash root of merle tree constructor( address _tokenUSDC, address _tokenBUMP, bytes32 _merkleRoot ) { require(_tokenUSDC != address(0), "Zero USDC address"); require(_tokenBUMP != address(0), "Zero BUMP address"); tokenUSDC = _tokenUSDC; tokenBUMP = _tokenBUMP; merkleRoot = _merkleRoot; // contract is paused by default _pause(); } /// @notice Pauses contract function pause() external onlyOwner { _pause(); } /// @notice Unpauses contract function unpause() external onlyOwner { _unpause(); } /// @notice Claim a specific amount of tokens. /// @param index Unique idendifier of tree record. Records with same index are not allowed /// @param account Air-droped tokens owner /// @param amountUSDC Amount of USDC tokens to claim /// @param amountBUMP Amount of BUMP tokens to claim /// @param merkleProof Proof of data accuracy function claim( uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] calldata merkleProof ) external whenNotPaused { _claim(index, account, amountUSDC, amountBUMP, merkleProof); } /// @notice Bulk token claim. /// @dev Can only be invoked if the escrow is NOT paused. /// @param claimArgs array encoded values (index, account, amount, timestamp, merkleProof) function claimBulk(bytes[] calldata claimArgs) external whenNotPaused { for (uint256 i = 0; i < claimArgs.length; i++) { (uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] memory merkleProof) = abi.decode( claimArgs[i], (uint256, address, uint256, uint256, bytes32[]) ); _claim(index, account, amountUSDC, amountBUMP, merkleProof); } } /// @notice Claim a specific amount of tokens. /// @param index Unique idendifier of tree record. Records with same index are not allowed /// @param account Air-droped tokens owner /// @param amountUSDC Amount of USDC tokens to claim /// @param amountBUMP Amount of BUMP tokens to claim /// @param merkleProof Proof of data accuracy function _claim( uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] memory merkleProof ) internal { require(merkleRoot != bytes32(0), "Merkle root not set"); require(!isClaimed(index), "Drop already claimed"); // Verify the merkle proof. bytes32 node = keccak256( abi.encodePacked(index, account, amountUSDC, amountBUMP) ); require( MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof" ); // Mark it claimed and send the token. _setClaimed(index); if (amountUSDC > 0) { IERC20(tokenUSDC).safeTransfer(account, amountUSDC); } if (amountBUMP > 0) { IERC20(tokenBUMP).safeTransfer(account, amountBUMP); } emit Claimed(index, account, amountUSDC, amountBUMP, block.timestamp); } /// @notice Withdraws tokens, stored on this contract to address function withdraw( address _to, address _token, uint256 _amount ) external onlyOwner { IERC20(_token).safeTransfer(_to, _amount); } /// @notice Updates merkle tree root hash function setMerkleRoot(bytes32 root) external onlyOwner { merkleRoot = root; } /// @notice Check for index been claimed or not function isClaimed(uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /// @dev set claimedBitMap mapping value to `true` function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } } // 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 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) { 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.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; 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 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; } }
Claim a specific amount of tokens. index Unique idendifier of tree record. Records with same index are not allowed account Air-droped tokens owner amountUSDC Amount of USDC tokens to claim amountBUMP Amount of BUMP tokens to claim merkleProof Proof of data accuracy Verify the merkle proof. Mark it claimed and send the token.
function _claim( uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] memory merkleProof ) internal { require(merkleRoot != bytes32(0), "Merkle root not set"); require(!isClaimed(index), "Drop already claimed"); bytes32 node = keccak256( abi.encodePacked(index, account, amountUSDC, amountBUMP) ); require( MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof" ); _setClaimed(index); if (amountUSDC > 0) { IERC20(tokenUSDC).safeTransfer(account, amountUSDC); } if (amountBUMP > 0) { IERC20(tokenBUMP).safeTransfer(account, amountBUMP); } emit Claimed(index, account, amountUSDC, amountBUMP, block.timestamp); }
14,578,451
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // IMPORTS // /** * @dev ERC721 token standard */ import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; /** * @dev Modifier 'onlyOwner' becomes available, where owner is the contract deployer */ import "@openzeppelin/contracts/access/Ownable.sol"; // CONTRACT // contract BARConsoles is ERC721Enumerable, Ownable { // %%%%%% uint256 public currentTokenId = 1; uint256 public MAX_SUPPLY = 5; // 2000 %%%%%%%%%%%%%%%%%%%%%%%%% uint256 public cost = 40000000000000000; // cost of minting uint256 public preSaleMintsTotal; // %%%%%%%%%% string public baseTokenURI; // %%%%%%%%%%%%%% bool public preSaleStatus = false; bool public generalSaleStatus = false; bool public claimStatus = false; // %%%%%%%%%%%%%%%%%%% string _name = 'BARConsolesTest'; string _symbol = 'BARCT'; string _uri = 'test'; // %%%%%%%%%%%%%%%%%%% constructor(/* %%%%%%%%%% string memory _name, string memory _symbol, string memory _uri */ ) ERC721(_name, _symbol) { baseTokenURI = _uri; } // EVENTS // event TokenBought(uint256 tokenId); // MAPPINGS // mapping(address => uint) whitelist; mapping(address => bool) claimList; // PUBLIC // function mint(uint256 _num) public payable { // %%%%%%%%%%%%% require(msg.value == _num * cost, "Incorrect funds supplied"); // mint cost if (preSaleStatus == true) { require(_num > 0 && _num <=2, "2 mint maximum"); require(whitelist[msg.sender] >= _num, "Not on whitelist or maximum of 2 mints per address allowed"); // checks if white listed & mint limit per address require(preSaleMintsTotal + _num <= 3, "Minting that many would exceed pre sale minting allocation"); // 250 in actual %%%%%%%%%%%%%%%%%%% whitelist[msg.sender] -= _num; preSaleMintsTotal += _num; } else { require(generalSaleStatus, "It's not time yet"); // checks general sale is live require(_num > 0 && _num <= 3, "Maximum of 3 mints allowed"); // mint limit per tx } for (uint256 i = 0; i < _num; i++) { uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; _mint(msg.sender, tokenId); emit TokenBought(tokenId); } } function claim() public { // %%%%%%%%%%%%%%% require(claimList[msg.sender], "Not on pre-approved claim list or have already claimed"); require(claimStatus, "It's not time yet"); uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; claimList[msg.sender] = false; // ensures they cannot claim a second time _mint(msg.sender, tokenId); emit TokenBought(tokenId); } // VIEW // /** * @dev Returns tokenURI which is comprised of the baseURI concatenated with the tokenId */ function tokenURI(uint256 _tokenId) public view override returns(string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } // ONLY OWNER // /** * @dev Withdraw ether from smart contract. Only contract owner can call. * @param _to - address ether will be sent to * @param _amount - amount of ether, in Wei, to be withdrawn (1 wei = 1e-18 ether) */ function withdrawFunds(address payable _to, uint _amount) external onlyOwner { require(_amount <= address(this).balance, "Withdrawal amount greater than balance"); _to.transfer(_amount); } /** * @dev Withdraw all ether from smart contract. Only contract owner can call. * @param _to - address ether will be sent to */ function withdrawAllFunds(address payable _to) external onlyOwner { require(address(this).balance > 0, "No funds to withdraw"); _to.transfer(address(this).balance); } /** * @dev Add addresses to white list, giving access to pre sale minting * @param _addresses - array of address' to add to white list mapping */ function whitelistAddresses(address[] calldata _addresses) external onlyOwner { for (uint i=0; i<_addresses.length; i++) { whitelist[_addresses[i]] = 2; } } /** * @dev Add addresses to claim list, giving access to claim function * @param _addresses - array of address' to add to claim list mapping */ function claimAddresses(address[] calldata _addresses) external onlyOwner { for (uint i=0; i<_addresses.length; i++) { claimList[_addresses[i]] = true; } } /** * @dev Airdrop 1 token to each address in array '_to' * @param _to - array of address' that tokens will be sent to */ function airDrop(address[] calldata _to) external onlyOwner { for (uint i=0; i<_to.length; i++) { uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; _mint(_to[i], tokenId); emit TokenBought(tokenId); } } /** * @dev Set the baseURI string */ function setBaseUri(string memory _newBaseUri) external onlyOwner { baseTokenURI = _newBaseUri; } /** * @dev Set the cost of minting a token * @param _newCost in Wei. Where 1 Wei = 10^-18 ether */ function setCost(uint _newCost) external onlyOwner { cost = _newCost; } /** * @dev Set the status of the pre sale * @param _status boolean where true = live */ function setPreSaleStatus(bool _status) external onlyOwner { preSaleStatus = _status; } /** * @dev Set the status of the general sale * @param _status boolean where true = live */ function setGeneralSaleStatus(bool _status) external onlyOwner { generalSaleStatus = _status; } /** * @dev Set the status of claim minitng * @param _status boolean where true = live */ function setClaimStatus(bool _status) external onlyOwner { claimStatus = _status; } /** * @dev Change the pre sale and claim status to over (false), and general sale status to live (true) */ function switchPreToGeneral() external onlyOwner { claimStatus = false; preSaleStatus = false; generalSaleStatus = true; } }
Set the status of claim minitng _status boolean where true = live/
function setClaimStatus(bool _status) external onlyOwner { claimStatus = _status; }
2,511,098
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/interface/IERC20Usdt.sol pragma solidity ^0.6.0; interface IERC20Usdt { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external; function transferFrom(address sender, address recipient, uint256 amount) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/Config.sol pragma solidity ^0.6.0; contract Config { // function signature of "postProcess()" bytes4 public constant POSTPROCESS_SIG = 0xc2722916; // The base amount of percentage function uint256 public constant PERCENTAGE_BASE = 1 ether; // Handler post-process type. Others should not happen now. enum HandlerType {Token, Custom, Others} } // File: contracts/lib/LibCache.sol pragma solidity ^0.6.0; library LibCache { function set( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, bytes32 _value ) internal { _cache[_key] = _value; } function setAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, address _value ) internal { _cache[_key] = bytes32(uint256(uint160(_value))); } function setUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, uint256 _value ) internal { _cache[_key] = bytes32(_value); } function getAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (address ret) { ret = address(uint160(uint256(_cache[_key]))); } function getUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (uint256 ret) { ret = uint256(_cache[_key]); } function get(mapping(bytes32 => bytes32) storage _cache, bytes32 _key) internal view returns (bytes32 ret) { ret = _cache[_key]; } } // File: contracts/lib/LibStack.sol pragma solidity ^0.6.0; library LibStack { function setAddress(bytes32[] storage _stack, address _input) internal { _stack.push(bytes32(uint256(uint160(_input)))); } function set(bytes32[] storage _stack, bytes32 _input) internal { _stack.push(_input); } function setHandlerType(bytes32[] storage _stack, Config.HandlerType _input) internal { _stack.push(bytes12(uint96(_input))); } function getAddress(bytes32[] storage _stack) internal returns (address ret) { ret = address(uint160(uint256(peek(_stack)))); _stack.pop(); } function getSig(bytes32[] storage _stack) internal returns (bytes4 ret) { ret = bytes4(peek(_stack)); _stack.pop(); } function get(bytes32[] storage _stack) internal returns (bytes32 ret) { ret = peek(_stack); _stack.pop(); } function peek(bytes32[] storage _stack) internal view returns (bytes32 ret) { require(_stack.length > 0, "stack empty"); ret = _stack[_stack.length - 1]; } } // File: contracts/Storage.sol pragma solidity ^0.6.0; /// @notice A cache structure composed by a bytes32 array contract Storage { using LibCache for mapping(bytes32 => bytes32); using LibStack for bytes32[]; bytes32[] public stack; mapping(bytes32 => bytes32) public cache; // keccak256 hash of "msg.sender" // prettier-ignore bytes32 public constant MSG_SENDER_KEY = 0xb2f2618cecbbb6e7468cc0f2aa43858ad8d153e0280b22285e28e853bb9d453a; // keccak256 hash of "cube.counter" // prettier-ignore bytes32 public constant CUBE_COUNTER_KEY = 0xf9543f11459ccccd21306c8881aaab675ff49d988c1162fd1dd9bbcdbe4446be; modifier isStackEmpty() { require(stack.length == 0, "Stack not empty"); _; } modifier isCubeCounterZero() { require(_getCubeCounter() == 0, "Cube counter not zero"); _; } modifier isInitialized() { require(_getSender() != address(0), "Sender is not initialized"); _; } modifier isNotInitialized() { require(_getSender() == address(0), "Sender is initialized"); _; } function _setSender() internal isNotInitialized { cache.setAddress(MSG_SENDER_KEY, msg.sender); } function _resetSender() internal { cache.setAddress(MSG_SENDER_KEY, address(0)); } function _getSender() internal view returns (address) { return cache.getAddress(MSG_SENDER_KEY); } function _addCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, _getCubeCounter() + 1); } function _resetCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, 0); } function _getCubeCounter() internal view returns (uint256) { return cache.getUint256(CUBE_COUNTER_KEY); } } // File: contracts/handlers/HandlerBase.sol pragma solidity ^0.6.0; abstract contract HandlerBase is Storage, Config { using SafeERC20 for IERC20; function postProcess() external payable virtual { revert("Invalid post process"); /* Implementation template bytes4 sig = stack.getSig(); if (sig == bytes4(keccak256(bytes("handlerFunction_1()")))) { // Do something } else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) { bytes32 temp = stack.get(); // Do something } else revert("Invalid post process"); */ } function _updateToken(address token) internal { stack.setAddress(token); // Ignore token type to fit old handlers // stack.setHandlerType(uint256(HandlerType.Token)); } function _updatePostProcess(bytes32[] memory params) internal { for (uint256 i = params.length; i > 0; i--) { stack.set(params[i - 1]); } stack.set(msg.sig); stack.setHandlerType(HandlerType.Custom); } function getContractName() public pure virtual returns (string memory); function _revertMsg(string memory functionName, string memory reason) internal view { revert( string( abi.encodePacked( _uint2String(_getCubeCounter()), "_", getContractName(), "_", functionName, ": ", reason ) ) ); } function _revertMsg(string memory functionName) internal view { _revertMsg(functionName, "Unspecified"); } function _uint2String(uint256 n) internal pure returns (string memory) { if (n == 0) { return "0"; } else { uint256 len = 0; for (uint256 temp = n; temp > 0; temp /= 10) { len++; } bytes memory str = new bytes(len); for (uint256 i = len; i > 0; i--) { str[i - 1] = bytes1(uint8(48 + (n % 10))); n /= 10; } return string(str); } } function _getBalance(address token, uint256 amount) internal view returns (uint256) { if (amount != uint256(-1)) { return amount; } // ETH case if ( token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ) { return address(this).balance; } // ERC20 token case return IERC20(token).balanceOf(address(this)); } function _tokenApprove( address token, address spender, uint256 amount ) internal { try IERC20Usdt(token).approve(spender, amount) {} catch { IERC20(token).safeApprove(spender, 0); IERC20(token).safeApprove(spender, amount); } } } // File: contracts/handlers/furucombo/IMerkleRedeem.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IMerkleRedeem { struct Claim { uint256 week; uint256 balance; bytes32[] merkleProof; } function token() external view returns (address); function claimWeeks(address, Claim[] calldata) external; } // File: contracts/handlers/furucombo/IStaking.sol pragma solidity ^0.6.0; interface IStaking { function stakingToken() external view returns (address); function redeemable() external view returns (address); function stakeFor(address, uint256) external; function unstakeFor(address, uint256) external; function claimWeeks(address, IMerkleRedeem.Claim[] calldata) external; } // File: contracts/handlers/furucombo/HFurucomboStaking.sol pragma solidity ^0.6.0; contract HFurucomboStaking is HandlerBase { using SafeERC20 for IERC20; function getContractName() public pure override returns (string memory) { return "HFurucomboStaking"; } function stake(address pool, uint256 amount) external payable { IStaking staking = IStaking(pool); address stakeToken = staking.stakingToken(); amount = _getBalance(stakeToken, amount); require(amount > 0, "HFurucombo: stake amount = 0"); IERC20(stakeToken).safeApprove(pool, amount); staking.stakeFor(_getSender(), amount); IERC20(stakeToken).safeApprove(pool, 0); } function unstake(address pool, uint256 amount) external payable { require(amount > 0, "HFurucombo: unstake amount = 0"); IStaking staking = IStaking(pool); staking.unstakeFor(_getSender(), amount); // Update involved token _updateToken(staking.stakingToken()); } function claimAll( address user, address[] calldata pools, IMerkleRedeem.Claim[][] calldata claims ) external payable { require(claims.length > 0, "HFurucombo: claims length = 0"); require( pools.length == claims.length, "HFurucombo: pools length != claims length" ); for (uint256 i = 0; i < claims.length; i++) { IMerkleRedeem redeem = IMerkleRedeem(pools[i]); redeem.claimWeeks(user, claims[i]); } } }
File: contracts/handlers/furucombo/IStaking.sol
interface IStaking { function stakingToken() external view returns (address); function redeemable() external view returns (address); function stakeFor(address, uint256) external; function unstakeFor(address, uint256) external; function claimWeeks(address, IMerkleRedeem.Claim[] calldata) external; }
1,559,520
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import "../../openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./module/PerpetualModule.sol"; import "./Type.sol"; import "./Storage.sol"; // @title Goovernance is the contract to maintain liquidityPool parameters. contract Governance is Storage { using SafeMathUpgradeable for uint256; using PerpetualModule for PerpetualStorage; using MarginAccountModule for PerpetualStorage; using LiquidityPoolModule for LiquidityPoolStorage; modifier onlyGovernor() { require(_msgSender() == _liquidityPool.governor, "only governor is allowed"); _; } modifier onlyOperator() { require(_msgSender() == _liquidityPool.getOperator(), "only operator is allowed"); _; } /** @notice */ function checkIn() public onlyOperator { _liquidityPool.checkIn(); } /** * @notice Use in a two phase operator transfer design: * 1. transfer operator to new operator; * 2. new operator claim to finish transfer. * Before claimOperator is called, operator wil remain to be the previous address. * * There are condition when calling transferring operator: * 1. when operator exists, only operator is able to call transfer; * 2. when operator not exists, call should be from a succeeded governor proposal. * @param newOperator The address of new operator to transfer to. */ function transferOperator(address newOperator) public { require(newOperator != address(0), "new operator is zero address"); address operator = _liquidityPool.getOperator(); if (operator != address(0)) { // has operator require(_msgSender() == operator, "can only be initiated by operator"); } else { require(_msgSender() == _liquidityPool.governor, "can only be initiated by governor"); } _liquidityPool.transferOperator(newOperator); } /** * @notice Set an address as keeper, who is able to call liquidate on bankrupt margin account. * If not set or set to zero address, keeper can be any one. * * @param newKeeper Address of new keeper. zero address means no limit to keeper only methods. */ function setKeeper(address newKeeper) public { address operator = _liquidityPool.getOperator(); if (operator != address(0)) { // has operator require(_msgSender() == operator, "can only be initiated by operator"); } else { require(_msgSender() == _liquidityPool.governor, "can only be initiated by governor"); } _liquidityPool.setKeeper(newKeeper); } /** * @notice Claim the ownership of the liquidity pool to sender. See `transferOperator` for details. * The caller must be the one specified by `transferOperator` first. */ function claimOperator() public { _liquidityPool.claimOperator(_msgSender()); } /** * @notice Revoke the operator of the liquidity pool. Can only called by the operator. */ function revokeOperator() public onlyOperator { _liquidityPool.revokeOperator(); } /** * @notice Set the parameter of the liquidity pool. Can only called by the governor. * @param params New values of parameter set. */ function setLiquidityPoolParameter(int256[2] calldata params) public onlyGovernor { _liquidityPool.setLiquidityPoolParameter(params); } function setOracle(uint256 perpetualIndex, address oracle) public onlyGovernor { _liquidityPool.setPerpetualOracle(perpetualIndex, oracle); } /** * @notice Set the base parameter of the perpetual. Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param baseParams Values of new base parameter set */ function setPerpetualBaseParameter(uint256 perpetualIndex, int256[9] calldata baseParams) public onlyGovernor { _liquidityPool.setPerpetualBaseParameter(perpetualIndex, baseParams); } /** * @notice Set the risk parameter and adjust range of the perpetual. Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param riskParams Values of new risk parameter set, each should be within range of related [min, max]. * @param minRiskParamValues Min values of new risk parameter. * @param maxRiskParamValues Max values of new risk parameter. */ function setPerpetualRiskParameter( uint256 perpetualIndex, int256[8] calldata riskParams, int256[8] calldata minRiskParamValues, int256[8] calldata maxRiskParamValues ) external onlyGovernor { _liquidityPool.setPerpetualRiskParameter( perpetualIndex, riskParams, minRiskParamValues, maxRiskParamValues ); } /** * @notice Update the risk parameter of the perpetual. Can only called by the operator * @param perpetualIndex The index of the perpetual in liquidity pool. * @param riskParams The new value of the risk parameter, must between minimum value and maximum value */ function updatePerpetualRiskParameter(uint256 perpetualIndex, int256[8] calldata riskParams) external onlyOperator { _liquidityPool.updatePerpetualRiskParameter(perpetualIndex, riskParams); } /** * @notice Force to set the state of the perpetual to "EMERGENCY" and set the settlement price. * Can only called by the governor. * @param perpetualIndex The index of the perpetual in liquidity pool. */ function forceToSetEmergencyState(uint256 perpetualIndex, int256 settlementPrice) external syncState(true) onlyGovernor { require(settlementPrice >= 0, "negative settlement price"); OraclePriceData memory settlementPriceData = OraclePriceData({ price: settlementPrice, time: block.timestamp }); PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex]; perpetual.markPriceData = settlementPriceData; perpetual.indexPriceData = settlementPriceData; _liquidityPool.setEmergencyState(perpetualIndex); } /** * @notice Set the state of the perpetual to "EMERGENCY". Can be call by anyone when * following conditions are met: * 1. the oralce contract declares itself as "termainated"; * 2. the AMM of perpetual's maintenance margin is unsafe; * @param perpetualIndex The index of the perpetual in liquidity pool. */ function setEmergencyState(uint256 perpetualIndex) public syncState(true) { if (perpetualIndex == Constant.SET_ALL_PERPETUALS_TO_EMERGENCY_STATE) { _liquidityPool.setAllPerpetualsToEmergencyState(); } else { PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex]; require(IOracle(perpetual.oracle).isTerminated(), "prerequisite not met"); _liquidityPool.setEmergencyState(perpetualIndex); } } bytes32[50] private __gap; }
Use in a two phase operator transfer design: 1. transfer operator to new operator; 2. new operator claim to finish transfer. Before claimOperator is called, operator wil remain to be the previous address. There are condition when calling transferring operator: 1. when operator exists, only operator is able to call transfer; 2. when operator not exists, call should be from a succeeded governor proposal. newOperator The address of new operator to transfer to./ has operator
function transferOperator(address newOperator) public { require(newOperator != address(0), "new operator is zero address"); address operator = _liquidityPool.getOperator(); if (operator != address(0)) { require(_msgSender() == operator, "can only be initiated by operator"); require(_msgSender() == _liquidityPool.governor, "can only be initiated by governor"); } _liquidityPool.transferOperator(newOperator); }
6,426,374
./partial_match/5/0x8dF9D355873b1cf8E9b05CEBF685f711f8Bc9f4D/sources/contracts/mixins/NFT721Metadata.sol
Contract constructor. When implementing this contract don't forget to set nftName and nftSymbol./
function _updateTokenNameAndSymbol(string memory _name, string memory _symbol) internal { nftName = _name; nftSymbol = _symbol; }
16,857,310
./full_match/4/0xB47d13DD287d0Da4E6A01C745b395890200262BA/sources/contracts/VRFAnimalLoot.sol
_safeMint(owner(), tokenId);
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 8788 && tokenId < 8889, "Token ID invalid"); requestRandomness(keyHash, fee); }
12,282,850
./full_match/1/0xa213C344D14e9aE9DA2b70a8f9A0122131d59274/sources/contracts/FutureQuest.sol
Verify Coupon Verify that the coupon sent was signed by the coupon signer and is a valid coupon Valid coupons will include coupon signer, address, and allotted mints Returns a boolean value digest The digest coupon The coupon/
function _isVerifiedCoupon(bytes32 digest, Coupon calldata coupon) private view returns (bool) { address signer = ecrecover(digest, coupon.v, coupon.r, coupon.s); require(signer != address(0), "Zero Address"); return signer == _couponSigner; }
8,357,605
pragma solidity ^0.4.18; // <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. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract SafeMath { function safeToAdd(uint a, uint b) pure internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) pure internal returns (uint) { require(safeToAdd(a, b)); return (a + b); } function safeToSubtract(uint a, uint b) pure internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) pure internal returns (uint) { require(safeToSubtract(a, b)); return (a - b); } } /** * @title token * @dev token function singnature */ contract token { function transfer(address receiver, uint amount){ receiver; amount; } } /** * @title Etherwow * @dev user choose a num in [2,99] system generate a num in [1,100], if num user choosed > num system generated, user win, otherwise user lose */ contract Etherwow is usingOraclize, SafeMath { using strings for *; /* * checks user profit, bet size and user number is within range */ modifier betIsValid(uint _betSize, uint _userNumber) { require(((((_betSize * (100-(safeSub(_userNumber,1)))) / (safeSub(_userNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize <= maxProfit && _betSize >= minBet && _userNumber >= minNumber && _userNumber <= maxNumber); _; } /* * checks game is currently active */ modifier gameIsActive { require(gamePaused == false); _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } /* * checks only owner address is calling */ modifier onlyOwner { require(msg.sender == owner); _; } /* * checks only owner address is calling */ modifier onlyOwnerOrOperator { require((msg.sender == owner || msg.sender == operator.addr) && msg.sender != 0x0); _; } /* * token vars */ token public jackpotToken; uint public jackpotTokenEthRate; uint public jackpotTokenWinRewardRate; uint public jackpotTokenLoseRewardRate; uint constant rewardRateDivisor = 1000; uint jackpotTokenReward; /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; uint public maxPendingPayouts; uint public randomQueryID; uint public randomGenerateMethod; string private randomApiKey; /* init discontinued contract data */ uint public totalBets = 0; uint public totalWeiWon = 0; uint public totalWeiWagered = 0; /* access control */ Operator public operator; struct Operator{ address addr; bool refundPermission; /* true - have permission, false - don't have permission */ uint refundAmtApprove; /* when refundAmtApprove not enough, use ownerModOperator() to set again */ } /* * user vars */ mapping (bytes32 => address) public userAddress; mapping (bytes32 => address) public userTempAddress; mapping (bytes32 => bytes32) public userBetId; mapping (bytes32 => uint) public userBetValue; mapping (bytes32 => uint) public userTempBetValue; mapping (bytes32 => uint) public userDieResult; mapping (bytes32 => uint) public userNumber; mapping (address => uint) public userPendingWithdrawals; mapping (bytes32 => uint) public userProfit; mapping (bytes32 => uint) public userTempReward; /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send, 5=pending, 6=manual refund */ mapping (bytes32 => uint8) public betStatus; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(bytes32 indexed BetID, address indexed UserAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint UserNumber, uint RandomQueryID); /* output to web3 UI on bet result*/ event LogResult(bytes32 indexed BetID, address indexed UserAddress, uint UserNumber, uint DiceResult, uint Value, uint tokenReward, uint8 Status, uint RandomGenerateMethod, bytes Proof, uint indexed SerialNumberOfResult); /* log manual refunds */ event LogRefund(bytes32 indexed BetID, address indexed UserAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); /* * init */ function Etherwow() { owner = msg.sender; oraclize_setNetwork(networkID_auto); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); /* init gas for oraclize */ gasForOraclize = 300000; /* init gas price for callback (default 20 gwei)*/ oraclize_setCustomGasPrice(20000000000 wei); /* defult random num generation method 0-random.org */ randomGenerateMethod = 0; } /* * @dev generate a true random num, two methods are provide, to avoid single point failure * randomGenerateMethod = 0 - random num generate from random.org * randomGenerateMethod = 1 - random num generate from oraclize service * @return oraclize queryId */ function generateRandomNum() internal returns(bytes32){ /* random num solution from random.org */ if (randomGenerateMethod == 0){ randomQueryID += 1; string memory queryString1 = "[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"serialNumber\",\"data\"]', '\\n{\"jsonrpc\":\"2.0\",\"method\":\"generateSignedIntegers\",\"params\":{\"apiKey\":"; string memory queryString1_1 = ",\"n\":1,\"min\":1,\"max\":100,\"replacement\":true,\"base\":10${[identity] \"}\"},\"id\":"; queryString1 = queryString1.toSlice().concat(randomApiKey.toSlice()); queryString1 = queryString1.toSlice().concat(queryString1_1.toSlice()); string memory queryString2 = uint2str(randomQueryID); string memory queryString3 = "${[identity] \"}\"}']"; string memory queryString1_2 = queryString1.toSlice().concat(queryString2.toSlice()); string memory queryString1_2_3 = queryString1_2.toSlice().concat(queryString3.toSlice()); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); return oraclize_query("nested", queryString1_2_3, gasForOraclize); } // /* random num solution from oraclize(by default), prove fair paper: http://www.oraclize.it/papers/random_datasource-rev1.pdf */ // if (randomGenerateMethod == 1){ // randomQueryID += 1; // uint N = 8; /* number of random bytes we want the datasource to return */ // uint delay = 0; /* number of seconds to wait before the execution takes place */ // oraclize_setProof(proofType_Ledger); // return oraclize_newRandomDSQuery(delay, N, gasForOraclize); /* this function internally generates the correct oraclize_query and returns its queryId */ // } } /* * @dev validate roll dice request, and log the bet info * @param number player choosen, from [2,99] * @param user address */ function userRollDice(uint rollUnder, address userAddr) public payable gameIsActive betIsValid(msg.value, rollUnder) { require((msg.value == 100000000000000000 && rollUnder == 76) || (msg.value == 200000000000000000 && rollUnder == 51) || (msg.value == 1000000000000000000 && rollUnder == 31) || (msg.value == 500000000000000000 && rollUnder == 16)); bytes32 rngId = generateRandomNum(); /* map bet id to this oraclize query */ userBetId[rngId] = rngId; /* map user lucky number to this oraclize query */ userNumber[rngId] = rollUnder; /* map value of wager to this oraclize query */ userBetValue[rngId] = msg.value; /* map user address to this oraclize query */ userAddress[rngId] = userAddr; /* safely map user profit to this oraclize query */ if (msg.value == 100000000000000000 && rollUnder == 76){ userProfit[rngId] = 20000000000000000; } if (msg.value == 200000000000000000 && rollUnder == 51){ userProfit[rngId] = 160000000000000000; } if (msg.value == 1000000000000000000 && rollUnder == 31){ userProfit[rngId] = 2000000000000000000; } if (msg.value == 500000000000000000 && rollUnder == 16){ userProfit[rngId] = 2500000000000000000; } /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, userProfit[rngId]); /* check contract can payout on win */ require(maxPendingPayouts < contractBalance); /* bet status = 5-pending */ betStatus[rngId] = 5; /* provides accurate numbers for web3 and allows for manual refunds in case of no oraclize __callback */ emit LogBet(userBetId[rngId], userAddress[rngId], safeAdd(userBetValue[rngId], userProfit[rngId]), userProfit[rngId], userBetValue[rngId], userNumber[rngId], randomQueryID); } /* * @dev oraclize callback, only oraclize can call, payout should in active status * @param queryId * @param query result * @param query proof */ function __callback(bytes32 myid, string result, bytes proof) public onlyOraclize { /* user address mapped to query id does not exist */ require(userAddress[myid]!=0x0); /* random num solution from random.org(by default) */ if (randomGenerateMethod == 0){ /* keep oraclize honest by retrieving the serialNumber from random.org result */ var sl_result = result.toSlice(); sl_result.beyond("[".toSlice()).until("]".toSlice()); uint serialNumberOfResult = parseInt(sl_result.split(', '.toSlice()).toString()); /* map random result to user */ userDieResult[myid] = parseInt(sl_result.beyond("[".toSlice()).until("]".toSlice()).toString()); } // /* random num solution from oraclize */ // if (randomGenerateMethod == 1){ // uint maxRange = 100; this is the highest uint we want to get. It should never be greater than 2^(8*N), where N is the number of random bytes we had asked the datasource to return // userDieResult[myid] = uint(sha3(result)) % maxRange + 1; /* this is an efficient way to get the uint out in the [0, maxRange] range */ // } /* get the userAddress for this query id */ userTempAddress[myid] = userAddress[myid]; /* delete userAddress for this query id */ delete userAddress[myid]; /* map the userProfit for this query id */ userTempReward[myid] = userProfit[myid]; /* set userProfit for this query id to 0 */ userProfit[myid] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, userTempReward[myid]); /* map the userBetValue for this query id */ userTempBetValue[myid] = userBetValue[myid]; /* set userBetValue for this query id to 0 */ userBetValue[myid] = 0; /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += userTempBetValue[myid]; /* * refund * if result is 0 result is empty or no proof refund original bet value * if refund fails save refund value to userPendingWithdrawals */ if(userDieResult[myid] == 0 || bytes(result).length == 0 || bytes(proof).length == 0){ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ /* 3 = refund */ betStatus[myid] = 3; /* * send refund - external call to an untrusted contract * if send fails map refund value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempBetValue[myid])){ /* 4 = refund + failed send */ betStatus[myid] = 4; /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempBetValue[myid]); } jackpotTokenReward = 0; emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to userPendingWithdrawals */ if(userDieResult[myid] < userNumber[myid]){ /* safely reduce contract balance by user profit */ contractBalance = safeSub(contractBalance, userTempReward[myid]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, userTempReward[myid]); /* safely calculate payout via profit plus original wager */ userTempReward[myid] = safeAdd(userTempReward[myid], userTempBetValue[myid]); /* 1 = win */ betStatus[myid] = 1; /* update maximum profit */ setMaxProfit(); if (jackpotTokenWinRewardRate > 0) { /* calculate win token return */ jackpotTokenReward = userTempBetValue[myid]*jackpotTokenEthRate*jackpotTokenWinRewardRate/rewardRateDivisor; /* transfer token to user */ jackpotToken.transfer(userTempAddress[myid], jackpotTokenReward); } /* * send win - external call to an untrusted contract * if send fails map reward value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempReward[myid])){ /* 2 = win + failed send */ betStatus[myid] = 2; /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempReward[myid]); } emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } /* * no win * send 1 wei to a losing bet * update contract balance to calculate new max bet */ if(userDieResult[myid] >= userNumber[myid]){ /* 0 = lose */ betStatus[myid] = 0; /* * safe adjust contractBalance * setMaxProfit * send 1 wei to losing bet */ contractBalance = safeAdd(contractBalance, (userTempBetValue[myid]-1)); /* update maximum profit */ setMaxProfit(); if (jackpotTokenLoseRewardRate > 0){ /* calculate token reward */ jackpotTokenReward = userTempBetValue[myid]*jackpotTokenEthRate*safeSub(100,userNumber[myid])*jackpotTokenLoseRewardRate/(rewardRateDivisor*100); /* transfer token to user */ jackpotToken.transfer(userTempAddress[myid], jackpotTokenReward); } /* * send 1 wei - external call to an untrusted contract */ if(!userTempAddress[myid].send(1)){ /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], 1); } emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } } /* * @dev in case of a failed refund or win send, user can withdraw later * @return true - withdraw success, false - withdraw failed */ function userWithdrawPendingTransactions() public gameIsActive returns (bool) { uint withdrawAmount = userPendingWithdrawals[msg.sender]; userPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert userPendingWithdrawals[msg.sender] = 0; */ /* user can try to withdraw again later */ userPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* * @dev in case of a failed refund or win send, user can check pending withdraw * @param address to check * @return pending withdraw amount */ function userGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return userPendingWithdrawals[addressToCheck]; } /* * @dev sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* * @dev fallback method */ function () payable onlyOwnerOrOperator { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* * @dev owner can set operator & permission * if want to revoke a permission, just set address to "0x0" * @param operator address * @param operator transfer permission * @param operator transfer approve amt * @param operator refund permission * @param operator refund approve amt */ function ownerModOperator(address newAddress, bool newRefundPermission, uint newRefundAmtApprove) public onlyOwner { operator.addr = newAddress; operator.refundPermission = newRefundPermission; operator.refundAmtApprove = newRefundAmtApprove; } /* * @dev onlyOwnerOrOperator set gas price for oraclize callback */ function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public onlyOwnerOrOperator { oraclize_setCustomGasPrice(newCallbackGasPrice); } /* * @dev onlyOwnerOrOperator set gas limit for oraclize query */ function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public onlyOwnerOrOperator { gasForOraclize = newSafeGasToOraclize; } /* * @dev onlyOwnerOrOperator adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwnerOrOperator { contractBalance = newContractBalanceInWei; } /* * @dev owner set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwnerOrOperator { if(msg.sender == operator.addr && newHouseEdge > 990) throw; houseEdge = newHouseEdge; } /* * @dev onlyOwnerOrOperator set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwnerOrOperator { /* restrict each bet to a maximum profit of 5% contractBalance */ require(newMaxProfitAsPercent <= 50000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* * @dev onlyOwnerOrOperator set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwnerOrOperator { minBet = newMinimumBet; } /* * @dev owner transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); sendTo.transfer(amount); emit LogOwnerTransfer(sendTo, amount); } /* * @dev manual refund * only onlyOwnerOrOperator address can do manual refund * used only if bet placed but not execute payout method after stock market close * filter LogBet by address and/or userBetId, do manual refund only when meet below conditions: * 1. bet status should be 5-pending; * 2. record should in logBet; * 3. record should not in logResult; * 4. record should not in logRefund; * if LogResult exists user should use the withdraw pattern userWithdrawPendingTransactions * if LogRefund exists means manual refund has been done before * @param betId * @param address sendTo * @param original user profit * @param original bet value */ function ownerRefundUser(bytes32 originalUserBetId, address sendTo, uint originalUserProfit, uint originalUserBetValue) public onlyOwnerOrOperator { /* check operator permission */ require(msg.sender == owner || (msg.sender == operator.addr && operator.refundPermission == true && safeToSubtract(operator.refundAmtApprove, originalUserBetValue))); /* status should be 5-pending */ require(betStatus[originalUserBetId] == 5); /* safely reduce pendingPayouts by userProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalUserProfit); /* send refund */ sendTo.transfer(originalUserBetValue); /* decrease approve amt if it's triggered by operator(no need to use safesub here, since passed above require() statement) */ if(msg.sender == operator.addr){ operator.refundAmtApprove = operator.refundAmtApprove - originalUserBetValue; } /* update betStatus = 6-manual refund */ betStatus[originalUserBetId] = 6; /* log refunds */ emit LogRefund(originalUserBetId, sendTo, originalUserBetValue); } /* * @dev onlyOwnerOrOperator set system emergency pause * @param true: pause, false: not pause */ function ownerPauseGame(bool newStatus) public onlyOwnerOrOperator { gamePaused = newStatus; } /* * @dev owner set new owner * @param new owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* * @dev onlyOwnerOrOperator set random.org api key * @param new api key */ function ownerSetRandomApiKey(string newApiKey) public onlyOwnerOrOperator { randomApiKey = newApiKey; } /* * @dev onlyOwnerOrOperator can set randomGenerateMethod * @param 0-random num solution from random.org, 1-random num solution from oraclize */ function ownerSetRandomGenerateMethod(uint newRandomGenerateMethod) public onlyOwnerOrOperator { randomGenerateMethod = newRandomGenerateMethod; } /* * @dev onlyOwnerOrOperator can set jackpotToken * @param jackpotToken address * @param ether to token rate * @param win reward rate, defult 10(divisor 1000) * @param lose reward rate, defult 1000(divisor 1000) */ function ownerSetJackpotToken(address newTokenAddr, uint newTokenEthRate, uint newWinRewardRate, uint newLoseRewardRate) public onlyOwnerOrOperator{ jackpotToken = token(newTokenAddr); jackpotTokenEthRate = newTokenEthRate; jackpotTokenWinRewardRate = newWinRewardRate; jackpotTokenLoseRewardRate = newLoseRewardRate; } /* * @dev transfer token * @param to address * @param token amount */ function ownerTransferJackpotToken(address toAddress, uint amount ) public onlyOwner{ jackpotToken.transfer(toAddress, amount); } /* * @dev owner selfdestruct contract ***BE CAREFUL! EMERGENCY ONLY / CONTRACT UPGRADE*** */ function ownerkill() public onlyOwner { selfdestruct(owner); } }
validate roll dice request, and log the bet info number player choosen, from [2,99] user address/ map bet id to this oraclize query / map user lucky number to this oraclize query / map value of wager to this oraclize query / map user address to this oraclize query / safely map user profit to this oraclize query /
function userRollDice(uint rollUnder, address userAddr) public payable gameIsActive betIsValid(msg.value, rollUnder) { require((msg.value == 100000000000000000 && rollUnder == 76) || (msg.value == 200000000000000000 && rollUnder == 51) || (msg.value == 1000000000000000000 && rollUnder == 31) || (msg.value == 500000000000000000 && rollUnder == 16)); bytes32 rngId = generateRandomNum(); userBetId[rngId] = rngId; userNumber[rngId] = rollUnder; userBetValue[rngId] = msg.value; userAddress[rngId] = userAddr; if (msg.value == 100000000000000000 && rollUnder == 76){ userProfit[rngId] = 20000000000000000; } if (msg.value == 200000000000000000 && rollUnder == 51){ userProfit[rngId] = 160000000000000000; } if (msg.value == 1000000000000000000 && rollUnder == 31){ userProfit[rngId] = 2000000000000000000; } if (msg.value == 500000000000000000 && rollUnder == 16){ userProfit[rngId] = 2500000000000000000; } }
12,184,478
/** *Submitted for verification at Etherscan.io on 2022-01-19 */ // Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/solidity/interface/INFTXEligibility.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // File contracts/solidity/token/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/solidity/proxy/IBeacon.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/interface/INFTXVaultFactory.sol pragma solidity ^0.8.0; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXVault.sol pragma solidity ^0.8.0; interface INFTXVault is IERC20Upgradeable { function manager() external view returns (address); function assetAddress() external view returns (address); function vaultFactory() external view returns (INFTXVaultFactory); function eligibilityStorage() external view returns (INFTXEligibility); function is1155() external view returns (bool); function allowAllItems() external view returns (bool); function enableMint() external view returns (bool); function enableRandomRedeem() external view returns (bool); function enableTargetRedeem() external view returns (bool); function enableRandomSwap() external view returns (bool); function enableTargetSwap() external view returns (bool); function vaultId() external view returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external view returns (uint256); function randomRedeemFee() external view returns (uint256); function targetRedeemFee() external view returns (uint256); function randomSwapFee() external view returns (uint256); function targetSwapFee() external view returns (uint256); function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event EnableRandomSwapUpdated(bool enabled); event EnableTargetSwapUpdated(bool enabled); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem, bool _enableRandomSwap, bool _enableTargetSwap ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee, uint256 _randomSwapFee, uint256 _targetSwapFee ) external; function disableVaultFees() external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // File contracts/solidity/interface/INFTXSimpleFeeDistributor.sol pragma solidity ^0.8.0; interface INFTXSimpleFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external view returns (address); function lpStaking() external view returns (address); function inventoryStaking() external view returns (address); function treasury() external view returns (address); function allocTotal() external view returns (uint256); // Write functions. function __SimpleFeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeReceiverAlloc(uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setLPStakingAddress(address _lpStaking) external; function setInventoryStakingAddress(address _inventoryStaking) external; function setNFTXVaultFactory(address _factory) external; } // File contracts/solidity/interface/INFTXLPStaking.sol pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakedToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXInventoryStaking.sol pragma solidity ^0.8.0; interface INFTXInventoryStaking { function nftxVaultFactory() external view returns (INFTXVaultFactory); function vaultXToken(uint256 vaultId) external view returns (address); function xTokenAddr(address baseToken) external view returns (address); function xTokenShareValue(uint256 vaultId) external view returns (uint256); function __NFTXInventoryStaking_init(address nftxFactory) external; function deployXTokenForVault(uint256 vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function timelockMintFor(uint256 vaultId, uint256 amount, address to, uint256 timelockLength) external returns (uint256); function deposit(uint256 vaultId, uint256 _amount) external; function withdraw(uint256 vaultId, uint256 _share) external; } // File contracts/solidity/interface/IUniswapV2Router01.sol pragma solidity ^0.8.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File contracts/solidity/testing/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/solidity/testing/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File contracts/solidity/interface/IERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/solidity/token/IERC1155Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File contracts/solidity/token/IERC721ReceiverUpgradeable.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/solidity/token/ERC721HolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is IERC721ReceiverUpgradeable { /** * @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; } } // File contracts/solidity/token/IERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File contracts/solidity/util/ERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is IERC165Upgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } } // File contracts/solidity/token/ERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is ERC165Upgradeable, IERC1155ReceiverUpgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } } // File contracts/solidity/token/ERC1155HolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155HolderUpgradeable is ERC1155ReceiverUpgradeable { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // File contracts/solidity/proxy/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 {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; } } } // File contracts/solidity/util/ContextUpgradeable.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 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/solidity/util/OwnableUpgradeable.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 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; } // File contracts/solidity/util/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/solidity/util/SafeERC20Upgradeable.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 SafeERC20Upgradeable { using Address for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/solidity/NFTXStakingZap.sol pragma solidity ^0.8.0; // Authors: @0xKiwi_. interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } /** * @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; } } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @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() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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); } } contract NFTXStakingZap is Ownable, ReentrancyGuard, ERC721HolderUpgradeable, ERC1155HolderUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; IWETH public immutable WETH; INFTXLPStaking public lpStaking; INFTXInventoryStaking public inventoryStaking; INFTXVaultFactory public immutable nftxFactory; IUniswapV2Router01 public immutable sushiRouter; uint256 public lpLockTime = 48 hours; uint256 public inventoryLockTime = 7 days; uint256 constant BASE = 1e18; event UserStaked(uint256 vaultId, uint256 count, uint256 lpBalance, uint256 timelockUntil, address sender); constructor(address _nftxFactory, address _sushiRouter) Ownable() ReentrancyGuard() { nftxFactory = INFTXVaultFactory(_nftxFactory); sushiRouter = IUniswapV2Router01(_sushiRouter); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); IERC20Upgradeable(address(IUniswapV2Router01(_sushiRouter).WETH())).safeApprove(_sushiRouter, type(uint256).max); } function assignStakingContracts() public { require(address(lpStaking) == address(0) || address(inventoryStaking) == address(0), "not zero"); lpStaking = INFTXLPStaking(INFTXSimpleFeeDistributor(INFTXVaultFactory(nftxFactory).feeDistributor()).lpStaking()); inventoryStaking = INFTXInventoryStaking(INFTXSimpleFeeDistributor(INFTXVaultFactory(nftxFactory).feeDistributor()).inventoryStaking()); } function setLPLockTime(uint256 newLPLockTime) external onlyOwner { require(newLPLockTime <= 7 days, "Lock too long"); lpLockTime = newLPLockTime; } function setInventoryLockTime(uint256 newInventoryLockTime) external onlyOwner { require(newInventoryLockTime <= 14 days, "Lock too long"); inventoryLockTime = newInventoryLockTime; } function provideInventory721(uint256 vaultId, uint256[] calldata tokenIds) external { uint256 count = tokenIds.length; INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); inventoryStaking.timelockMintFor(vaultId, count*BASE, msg.sender, inventoryLockTime); address xToken = inventoryStaking.vaultXToken(vaultId); uint256 oldBal = IERC20Upgradeable(vault).balanceOf(xToken); uint256[] memory amounts = new uint256[](0); address assetAddress = vault.assetAddress(); uint256 length = tokenIds.length; for (uint256 i; i < length; ++i) { transferFromERC721(assetAddress, tokenIds[i], address(vault)); approveERC721(assetAddress, address(vault), tokenIds[i]); } vault.mintTo(tokenIds, amounts, address(xToken)); uint256 newBal = IERC20Upgradeable(vault).balanceOf(xToken); require(newBal == oldBal + count*BASE, "Incorrect vtokens minted"); } function provideInventory1155(uint256 vaultId, uint256[] calldata tokenIds, uint256[] calldata amounts) external { uint256 length = tokenIds.length; require(length == amounts.length, "Not equal length"); uint256 count; for (uint256 i; i < length; ++i) { count += amounts[i]; } INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); inventoryStaking.timelockMintFor(vaultId, count*BASE, msg.sender, inventoryLockTime); address xToken = inventoryStaking.vaultXToken(vaultId); uint256 oldBal = IERC20Upgradeable(vault).balanceOf(address(xToken)); IERC1155Upgradeable nft = IERC1155Upgradeable(vault.assetAddress()); nft.safeBatchTransferFrom(msg.sender, address(this), tokenIds, amounts, ""); nft.setApprovalForAll(address(vault), true); vault.mintTo(tokenIds, amounts, address(xToken)); uint256 newBal = IERC20Upgradeable(vault).balanceOf(address(xToken)); require(newBal == oldBal + count*BASE, "Incorrect vtokens minted"); } function addLiquidity721ETH( uint256 vaultId, uint256[] calldata ids, uint256 minWethIn ) external payable returns (uint256) { return addLiquidity721ETHTo(vaultId, ids, minWethIn, msg.sender); } function addLiquidity721ETHTo( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, address to ) public payable nonReentrant returns (uint256) { require(to != address(0) && to != address(this)); WETH.deposit{value: msg.value}(); (, uint256 amountEth, uint256 liquidity) = _addLiquidity721WETH(vaultId, ids, minWethIn, msg.value, to); // Return extras. uint256 remaining = msg.value-amountEth; if (remaining != 0) { WETH.withdraw(remaining); (bool success, ) = payable(to).call{value: remaining}(""); require(success, "Address: unable to send value, recipient may have reverted"); } return liquidity; } function addLiquidity1155ETH( uint256 vaultId, uint256[] calldata ids, uint256[] calldata amounts, uint256 minEthIn ) external payable returns (uint256) { return addLiquidity1155ETHTo(vaultId, ids, amounts, minEthIn, msg.sender); } function addLiquidity1155ETHTo( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minEthIn, address to ) public payable nonReentrant returns (uint256) { require(to != address(0) && to != address(this)); WETH.deposit{value: msg.value}(); // Finish this. (, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value, to); // Return extras. uint256 remaining = msg.value-amountEth; if (remaining != 0) { WETH.withdraw(remaining); (bool success, ) = payable(to).call{value: remaining}(""); require(success, "Address: unable to send value, recipient may have reverted"); } return liquidity; } function addLiquidity721( uint256 vaultId, uint256[] calldata ids, uint256 minWethIn, uint256 wethIn ) external returns (uint256) { return addLiquidity721To(vaultId, ids, minWethIn, wethIn, msg.sender); } function addLiquidity721To( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn, address to ) public nonReentrant returns (uint256) { require(to != address(0) && to != address(this)); IERC20Upgradeable(address(WETH)).safeTransferFrom(msg.sender, address(this), wethIn); (, uint256 amountEth, uint256 liquidity) = _addLiquidity721WETH(vaultId, ids, minWethIn, wethIn, to); // Return extras. uint256 remaining = wethIn-amountEth; if (remaining != 0) { WETH.transfer(to, remaining); } return liquidity; } function addLiquidity1155( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn ) public returns (uint256) { return addLiquidity1155To(vaultId, ids, amounts, minWethIn, wethIn, msg.sender); } function addLiquidity1155To( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn, address to ) public nonReentrant returns (uint256) { require(to != address(0) && to != address(this)); IERC20Upgradeable(address(WETH)).safeTransferFrom(msg.sender, address(this), wethIn); (, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minWethIn, wethIn, to); // Return extras. uint256 remaining = wethIn-amountEth; if (remaining != 0) { WETH.transfer(to, remaining); } return liquidity; } function _addLiquidity721WETH( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn, address to ) internal returns (uint256, uint256, uint256) { require(nftxFactory.excludedFromFees(address(this))); address vault = nftxFactory.vault(vaultId); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); uint256 length = ids.length; for (uint256 i; i < length; i++) { transferFromERC721(assetAddress, ids[i], vault); approveERC721(assetAddress, vault, ids[i]); } uint256[] memory emptyIds; INFTXVault(vault).mint(ids, emptyIds); uint256 balance = length * BASE; // We should not be experiencing fees. return _addLiquidityAndLock(vaultId, vault, balance, minWethIn, wethIn, to); } function _addLiquidity1155WETH( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn, address to ) internal returns (uint256, uint256, uint256) { require(nftxFactory.excludedFromFees(address(this))); address vault = nftxFactory.vault(vaultId); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(msg.sender, address(this), ids, amounts, ""); IERC1155Upgradeable(assetAddress).setApprovalForAll(vault, true); uint256 count = INFTXVault(vault).mint(ids, amounts); uint256 balance = (count * BASE); // We should not be experiencing fees. return _addLiquidityAndLock(vaultId, vault, balance, minWethIn, wethIn, to); } function _addLiquidityAndLock( uint256 vaultId, address vault, uint256 minTokenIn, uint256 minWethIn, uint256 wethIn, address to ) internal returns (uint256, uint256, uint256) { // Provide liquidity. IERC20Upgradeable(vault).safeApprove(address(sushiRouter), minTokenIn); (uint256 amountToken, uint256 amountEth, uint256 liquidity) = sushiRouter.addLiquidity( address(vault), address(WETH), minTokenIn, wethIn, minTokenIn, minWethIn, address(this), block.timestamp ); // Stake in LP rewards contract address lpToken = pairFor(vault, address(WETH)); IERC20Upgradeable(lpToken).safeApprove(address(lpStaking), liquidity); lpStaking.timelockDepositFor(vaultId, to, liquidity, lpLockTime); uint256 remaining = minTokenIn-amountToken; if (remaining != 0) { IERC20Upgradeable(vault).safeTransfer(to, remaining); } uint256 lockEndTime = block.timestamp + lpLockTime; emit UserStaked(vaultId, minTokenIn, liquidity, lockEndTime, to); return (amountToken, amountEth, liquidity); } // function removeLiquidity( // address tokenA, // address tokenB, // uint256 liquidity, // uint256 amountAMin, // uint256 amountBMin, // address to, // uint256 deadline // ) external returns (uint256 amountA, uint256 amountB); // function removeLiquidityETH( // address token, // uint256 liquidity, // uint256 amountTokenMin, // uint256 amountETHMin, // address to, // uint256 deadline // ) external returns (uint256 amountToken, uint256 amountETH); function _removeLiquidityAndLock( uint256 vaultId, address vault, uint256 minTokenIn, uint256 minWethIn, uint256 wethIn, address to ) internal returns (uint256, uint256, uint256) { // Provide liquidity. IERC20Upgradeable(vault).safeApprove(address(sushiRouter), minTokenIn); (uint256 amountToken, uint256 amountEth, uint256 liquidity) = sushiRouter.addLiquidity( address(vault), address(WETH), minTokenIn, wethIn, minTokenIn, minWethIn, address(this), block.timestamp ); // Stake in LP rewards contract address lpToken = pairFor(vault, address(WETH)); IERC20Upgradeable(lpToken).safeApprove(address(lpStaking), liquidity); lpStaking.timelockDepositFor(vaultId, to, liquidity, lpLockTime); uint256 remaining = minTokenIn-amountToken; if (remaining != 0) { IERC20Upgradeable(vault).safeTransfer(to, remaining); } uint256 lockEndTime = block.timestamp + lpLockTime; emit UserStaked(vaultId, minTokenIn, liquidity, lockEndTime, to); return (amountToken, amountEth, liquidity); } function transferFromERC721(address assetAddr, uint256 tokenId, address to) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, to, tokenId); } else if (assetAddr == punks) { // CryptoPunks. // Fix here for frontrun attack. Added in v1.0.2. bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address nftOwner) = abi.decode(result, (address)); require(checkSuccess && nftOwner == msg.sender, "Not the NFT owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId); } else { // Default. // We push to the vault to avoid an unneeded transfer. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, to, tokenId); } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } function approveERC721(address assetAddr, address to, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. // data = abi.encodeWithSignature("approve(address,uint256)", to, tokenId); // No longer needed to approve with pushing. return; } else if (assetAddr == punks) { // CryptoPunks. data = abi.encodeWithSignature("offerPunkForSaleToAddress(uint256,uint256,address)", tokenId, 0, to); } else { // No longer needed to approve with pushing. return; } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', sushiRouter.factory(), keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash ))))); } // 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'); } receive() external payable { require(msg.sender == address(WETH), "Only WETH"); } function rescue(address token) external onlyOwner { if (token == address(0)) { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "Address: unable to send value, recipient may have reverted"); } else { IERC20Upgradeable(token).safeTransfer(msg.sender, IERC20Upgradeable(token).balanceOf(address(this))); } } }
Cryptokitties. data = abi.encodeWithSignature("approve(address,uint256)", to, tokenId); No longer needed to approve with pushing. CryptoPunks. No longer needed to approve with pushing.
function approveERC721(address assetAddr, address to, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { return; data = abi.encodeWithSignature("offerPunkForSaleToAddress(uint256,uint256,address)", tokenId, 0, to); return; } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); }
6,707,653
./full_match/1/0x5C1Dbcb680f19b66907effD9F291880a4776d592/sources/contracts/diamond/abstracts/AccessControl.sol
Grants `role` to `account`. Internal function without access restriction. May emit a {RoleGranted} event./
function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { s.roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } }
4,974,017
/** * Source Code first verified at https://etherscan.io on Friday, April 26, 2019 (UTC) */ pragma solidity >=0.4.22 <0.6.0; /** * @title SafeMath * Math operations with safety checks that throw on error */ library SafeMath { /** * Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * 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; } /** * 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; } /** * Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } address public owner; constructor() public { owner = msg.sender; } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } modifier onlyOwner { require(msg.sender == owner); _; } } contract TokenERC20 is Ownable { using SafeMath for uint256; // Public variables of the token address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } string public name; mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } string public symbol; address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ if (!(lastPlayer_re_ent9.send(jackpot_re_ent9))) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } uint8 public decimals; mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } uint256 private _totalSupply; mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } uint256 public cap; // This creates an array with all balances mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent26[msg.sender]) ) ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } mapping (address => uint256) private _balances; bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } mapping (address => mapping (address => uint256)) private _allowed; // This generates a public event on the blockchain that will notify clients bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event Approval(address indexed owner, address indexed spender, uint256 value); // This generates a public event on the blockchain that will notify clients bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent13 = false; } event Mint(address indexed to, uint256 amount); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 _cap, uint256 _initialSupply, string memory _name, string memory _symbol, uint8 _decimals ) public { require(_cap >= _initialSupply); cap = _cap; name = _name; // Set the cap of total supply symbol = _symbol; // Set the symbol for display purposes decimals = _decimals; // Set the decimals _totalSupply = _initialSupply; // Update total supply with the decimal amount _balances[owner] = _totalSupply; // Give the creator all initial tokens emit Transfer(address(0), owner, _totalSupply); } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } /** * Total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return _totalSupply; } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } /** * Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return _balances[_owner]; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } /** * 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]; } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } /** * Transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } /** * 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) { _approve(msg.sender, _spender, _value); return true; } address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } /** * Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { _transfer(_from, _to, _value); _approve(_from, msg.sender, _allowed[_from][msg.sender].sub(_value)); return true; } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { if (msg.sender.send(balances_re_ent8[msg.sender ])) balances_re_ent8[msg.sender] = 0; } /** * Transfer token for a specified addresses. * @param _from The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0), "ERC20: transfer to the zero address"); _balances[_from] = _balances[_from].sub(_value); _balances[_to] = _balances[_to].add(_value); emit Transfer(_from, _to, _value); } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } /** * Approve an address to spend another addresses' tokens. * @param _owner The address that owns the tokens. * @param _spender The address that will spend the tokens. * @param _value The number of tokens that can be spent. */ function _approve(address _owner, address _spender, uint256 _value) internal { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); _allowed[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } /** * 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 public returns (bool) { require(_totalSupply.add(_amount) <= cap); _totalSupply = _totalSupply.add(_amount); _balances[_to] = _balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } /** * Transfer token to servral addresses. * @param _tos The addresses to transfer to. * @param _values The amounts to be transferred. */ function transferBatch(address[] memory _tos, uint256[] memory _values) public returns (bool) { require(_tos.length == _values.length); for (uint256 i = 0; i < _tos.length; i++) { transfer(_tos[i], _values[i]); } return true; } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent40[msg.sender]) ) ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } } /******************************************/ /* XLToken TOKEN STARTS HERE */ /******************************************/ contract XLToken is TokenERC20 { /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() TokenERC20(18*10**16, 12*10**16, "XL Token", "XL", 8) public {} mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent33[msg.sender]) ) ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } }
send userBalance[msg.sender] ethers to msg.sender if mgs.sender is a contract, it will call its fallback function
function withdrawBalance_re_ent19() public{ if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } uint256 public cap;
951,843
./full_match/80001/0xF9db858E9958dDd5795571558C5c585E2683FB75/sources/contracts/ParagonsDAOPlayerID.sol
Returns Base64 encoded JSON for ERC721 Token URI.
function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert NoPDP(); return constructTokenURI(tokenId); } OWNER FUNCTIONS
843,785
/** *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 ); } }
Decreases internal data structure which tracks free bond per archaeologist data the system's data struct instance archAddress the archaeologist's address to operate on amount the amount to decrease free bond by/ load up the archaeologist decrease the free bond variable by amount, reverting if necessary
function decreaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount ) private { Types.Archaeologist storage arch = data.archaeologists[archAddress]; require( arch.freeBond >= amount, "archaeologist does not have enough free bond" ); arch.freeBond = arch.freeBond - amount; }
2,451,153
./full_match/8453/0x1a920B29eBD437074225cAeE44f78FC700B27a5d/sources/contracts/AxelarGateway.sol
AUDIT: If `newImplementation.setup` performs `selfdestruct`, it will result in the loss of _this_ implementation (thereby losing the gateway) if `upgrade` is entered within the context of _this_ implementation itself. solhint-disable-next-line avoid-low-level-calls
function upgrade( address newImplementation, bytes32 newImplementationCodeHash, bytes calldata setupParams ) external override onlyAdmin { if (newImplementationCodeHash != newImplementation.codehash) revert InvalidCodeHash(); emit Upgraded(newImplementation); if (setupParams.length != 0) { (bool success, ) = newImplementation.delegatecall(abi.encodeWithSelector(IAxelarGateway.setup.selector, setupParams)); if (!success) revert SetupFailed(); } _setImplementation(newImplementation); } \**********************/
11,536,157
pragma solidity ^0.5.10; // File: openzeppelin-solidity/contracts/math/SafeMath.sol library SafeMath { function ADD174(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB458(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function MUL842(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV712(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD1000(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface IERC20 { function TOTALSUPPLY713() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF597(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER875(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE411(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE183(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM17(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER72(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL424(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED585(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED585(address(0), _owner); } function OWNER749() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER904() { //inject NONSTANDARD NAMING require(ISOWNER531(), "Ownable: caller is not the owner"); _; } function ISOWNER531() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP876() public ONLYOWNER904 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED585(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP672(address newOwner) public ONLYOWNER904 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP705(newOwner); } function _TRANSFEROWNERSHIP705(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED585(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol contract TokenRecover is Ownable { function RECOVERERC20610(address tokenAddress, uint256 tokenAmount) public ONLYOWNER904 { //inject NONSTANDARD NAMING IERC20(tokenAddress).TRANSFER875(OWNER749(), tokenAmount); } } // File: openzeppelin-solidity/contracts/access/Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } function ADD174(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(!HAS393(role, account), "Roles: account already has role"); role.bearer[account] = true; } function REMOVE440(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(HAS393(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function HAS393(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/access/roles/OperatorRole.sol contract OperatorRole { using Roles for Roles.Role; event OPERATORADDED296(address indexed account); //inject NONSTANDARD NAMING event OPERATORREMOVED455(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _operators; constructor() internal { _ADDOPERATOR180(msg.sender); } modifier ONLYOPERATOR220() { //inject NONSTANDARD NAMING require(ISOPERATOR589(msg.sender)); _; } function ISOPERATOR589(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _operators.HAS393(account); } function ADDOPERATOR496(address account) public ONLYOPERATOR220 { //inject NONSTANDARD NAMING _ADDOPERATOR180(account); } function RENOUNCEOPERATOR579() public { //inject NONSTANDARD NAMING _REMOVEOPERATOR220(msg.sender); } function _ADDOPERATOR180(address account) internal { //inject NONSTANDARD NAMING _operators.ADD174(account); emit OPERATORADDED296(account); } function _REMOVEOPERATOR220(address account) internal { //inject NONSTANDARD NAMING _operators.REMOVE440(account); emit OPERATORREMOVED455(account); } } // File: contracts/utils/Contributions.sol contract Contributions is OperatorRole, TokenRecover { using SafeMath for uint256; struct Contributor { uint256 weiAmount; uint256 tokenAmount; bool exists; } // the number of sold tokens uint256 private _totalSoldTokens; // the number of wei raised uint256 private _totalWeiRaised; // list of addresses who contributed in crowdsales address[] private _addresses; // map of contributors mapping(address => Contributor) private _contributors; constructor() public {} // solhint-disable-line no-empty-blocks function TOTALSOLDTOKENS700() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSoldTokens; } function TOTALWEIRAISED967() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalWeiRaised; } function GETCONTRIBUTORADDRESS38(uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _addresses[index]; } function GETCONTRIBUTORSLENGTH778() public view returns (uint) { //inject NONSTANDARD NAMING return _addresses.length; } function WEICONTRIBUTION247(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _contributors[account].weiAmount; } function TOKENBALANCE103(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _contributors[account].tokenAmount; } function CONTRIBUTOREXISTS747(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _contributors[account].exists; } function ADDBALANCE147(address account, uint256 weiAmount, uint256 tokenAmount) public ONLYOPERATOR220 { //inject NONSTANDARD NAMING if (!_contributors[account].exists) { _addresses.push(account); _contributors[account].exists = true; } _contributors[account].weiAmount = _contributors[account].weiAmount.ADD174(weiAmount); _contributors[account].tokenAmount = _contributors[account].tokenAmount.ADD174(tokenAmount); _totalWeiRaised = _totalWeiRaised.ADD174(weiAmount); _totalSoldTokens = _totalSoldTokens.ADD174(tokenAmount); } function REMOVEOPERATOR69(address account) public ONLYOWNER904 { //inject NONSTANDARD NAMING _REMOVEOPERATOR220(account); } }
inject NONSTANDARD NAMING
function APPROVE183(address spender, uint256 amount) external returns (bool);
13,026,270
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract TheRebirth is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedURI; string public redeemedURI; uint256 public cost = 0.2 ether; uint256 public immutable numberOfSeries = 8; // number of "spirits" or sub-series in the collection uint256 public immutable maxSupply = 4000; // collection max supply uint256 private immutable seriesLimit = 500; // maximum 500 NFT per "spirit" or sub-series uint256 public privateSaleAllocation = 111; // number of full sets allocated for the private sale uint256 public privateSaleCounter; // tracks the number of full sets minted during the private sale uint256 private immutable seriesPerAddressLimit = 2; // number of NFTs from a "spirit" or sub-series that can be minted by a single address uint256 private mintPerAddressLimit = 16; // max number of NFTs a single address can mint bool public paused; // indicates whether the contract has been paused bool public revealed; // indicates whether the collection has been revealed bool private reserveMinted; // counts the number of sets that has been minted during the private sale period bool public onlyWhitelisted = true; // indicates whether the private sale period is in effect mapping(uint256 => uint256) public seriesCounter; // trakcs the number of tokens minted for a particular "spirit" or sub-series mapping(uint256 => uint256) public seriesTokenId; // increments the tokenId for each "spirit" or sub-series as they are minted mapping(address => uint256) public addressMintedBalance; // tracks the number of NFTs minted by a given address mapping(address => uint256[8]) public seriesPerAddressCounter; // this tracks the number of NFTs minted by "spirit" or sub-series for each address mapping(address => bool) public whitelistedAddresses; // tracks whether a given address is allowed to bundlemint during the private sale mapping(uint256 => bool) public redeemedTokens; // tracks whether a particular NFT of tokenId has been redeemed constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedURI, string memory _initRedeemedURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedURI); _setRedeemedURI(_initRedeemedURI); seriesTokenId[1] = 1; seriesTokenId[2] = 501; seriesTokenId[3] = 1001; seriesTokenId[4] = 1501; seriesTokenId[5] = 2001; seriesTokenId[6] = 2501; seriesTokenId[7] = 3001; seriesTokenId[8] = 3501; } /****** public *******/ // single mint function mint(uint256 _seriesType) public payable nonReentrant{ require(!paused, "the contract is paused"); require(_seriesType > 0 && _seriesType <= numberOfSeries, "incorrect series identifier, value should be an integer between 1 and 8 "); require(seriesCounter[_seriesType] < seriesLimit, "this series type has been sold out"); uint256 supply = totalSupply(); require(supply < maxSupply, "max NFT limit exceeded"); // total supply must not exceed 4000 if (msg.sender != owner()) { require(onlyWhitelisted == false, "the public sale is not currently active"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount < mintPerAddressLimit, "max NFT per address exceeded"); require(seriesPerAddressCounter[msg.sender][_seriesType-1] < seriesPerAddressLimit , "this address has minted the maximum allowable number of tokens for this series"); require(msg.value >= cost, "insufficient funds"); if ( msg.value > cost ){ address payable refund = payable(msg.sender); refund.transfer(msg.value - cost); } } // mint single NFT of sub-series type _seriesType uint256 tokenId = seriesTokenId[_seriesType]; // tokenId to be assigned to the NFT being safe minted seriesTokenId[_seriesType]++; // sub-series tokenId is incremented seriesCounter[_seriesType]++; // sub-series mint count is incremented seriesPerAddressCounter[msg.sender][_seriesType-1]++; // number of NFTs in the sub-series minted by the msg.sender is incremented addressMintedBalance[msg.sender]++; // number of NFTs minted by the msg.sender is incremente _safeMint(msg.sender, tokenId); } // bundle mint function bundleMint() public payable nonReentrant{ require(!paused, "the contract is paused"); uint256 supply = totalSupply(); require(supply + numberOfSeries <= maxSupply, "max NFT limit exceeded"); for (uint256 i = 1; i <= numberOfSeries; i++){ // prohibit batch mint if any of the sub-series has been sold out require(seriesCounter[i] < seriesLimit, "one or more series sold out, bundle mint no longer available"); if (msg.sender != owner()) { // prohibit batch mint if address holds the maximum allowable number of tokens for any given sub-series require(seriesPerAddressCounter[msg.sender][i-1] < seriesPerAddressLimit , "this address has minted the maximum allowable number of tokens for a given series"); } } if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted, or max minting allowance for private sale exceeded"); require(privateSaleCounter < privateSaleAllocation, "private sale allocation has been sold out"); } // check whitelist logic uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + numberOfSeries <= mintPerAddressLimit, "max NFT per address exceeded, consider minting single NFT"); require(msg.value >= (cost * numberOfSeries), "insufficient funds"); if ( msg.value > (cost * numberOfSeries)){ address payable refund = payable(msg.sender); refund.transfer(msg.value - (cost * numberOfSeries)); } } // update all counters prior to safe minting NFTs addressMintedBalance[msg.sender] += numberOfSeries; uint256[8] memory tokenId; for (uint256 i = 1; i <= numberOfSeries; i++) { tokenId[i-1] = seriesTokenId[i]; // tokenId for each "spirit" or sub-series is stored in tokenId array seriesTokenId[i]++; // the tokenId of each "spirit" or sub-series is incremented seriesCounter[i]++; // the mint count of each "spirit" or sub-series is incremented seriesPerAddressCounter[msg.sender][i-1]++; // the mint count of each "spirit" or sub-series for a particular address is incremented } // mint one NFT for each of the eight sub-series for (uint256 i = 1; i <= numberOfSeries; i++) { _safeMint(msg.sender, tokenId[i-1]); // mint the tokens according to the Ids stored in the tokenId array } // remove address from whitelist following private sale minting if( (onlyWhitelisted == true) && (msg.sender != owner()) ) { whitelistedAddresses[msg.sender] = false; privateSaleCounter++; } } // indicates whether a paticular address is on the whitelist function isWhitelisted(address _user) public view returns (bool) { return whitelistedAddresses[_user]; } // returns the tokenId of NFTs belonging to the particular address function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); // not revealed URI if(revealed == false) { return bytes(notRevealedURI).length > 0 ? string(abi.encodePacked(notRevealedURI, tokenId.toString(), baseExtension)) : ""; } // redemption URI if (redeemedTokens[tokenId]) { return bytes(redeemedURI).length > 0 ? string(abi.encodePacked(redeemedURI, tokenId.toString(), baseExtension)) : ""; } // base URI string memory currentBaseURI = baseURI; return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } /****** onlyOwner *******/ function mintReserve() public onlyOwner nonReentrant{ require(!reserveMinted,"the reserve can only be minted once"); for (uint256 bundle = 1; bundle <= 14; bundle++){ for (uint256 i = 1; i <= numberOfSeries; i++) { addressMintedBalance[msg.sender]++; uint256 tokenId = seriesTokenId[i]; seriesTokenId[i]++; seriesCounter[i]++; _safeMint(msg.sender, tokenId); } } reserveMinted = true; } function reveal() public onlyOwner { revealed = true; } function initiatePublicSale() public onlyOwner { onlyWhitelisted = false; } function setPrivateSaleAllocation(uint256 _bundleLimit) public onlyOwner { privateSaleAllocation = _bundleLimit; } function setMintPerAddressLimit(uint256 _limit) public onlyOwner { mintPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedURI = _notRevealedURI; } function _setRedeemedURI(string memory _initRedeemedURI) private { redeemedURI = _initRedeemedURI; } // onlyOwner call for changing redemption status of token and updates the redeemed token URI function setRedemptionStatus(uint256 _tokenId, bool _state, string memory _redeemedURI) public onlyOwner { require(_state == true || _state == false, "_state must be true or false"); redeemedTokens[_tokenId] = _state; _setRedeemedURI(_redeemedURI); } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { for (uint i = 0; i < _users.length; i++) { whitelistedAddresses[_users[i]] = true; } } function removeFromWhitelist(address[] calldata _users) public onlyOwner { for (uint i = 0; i < _users.length; i++) { whitelistedAddresses[_users[i]] = false; } } function withdraw(address _address) public payable onlyOwner { (bool os, ) = payable(_address).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) 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 // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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 // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/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/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 (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); }
not revealed URI redemption URI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return bytes(notRevealedURI).length > 0 ? string(abi.encodePacked(notRevealedURI, tokenId.toString(), baseExtension)) : ""; } if (redeemedTokens[tokenId]) { return bytes(redeemedURI).length > 0 ? string(abi.encodePacked(redeemedURI, tokenId.toString(), baseExtension)) : ""; } return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; }
7,015,585
./full_match/5/0xCf86e56b395032163dd4Af966500e2F189f29637/sources/contracts/contracts-V6/src/StandardCampaign.sol
Donate to a campaign โœ…
function fundCampaign( uint256 _id, uint256 _funding ) public payable isMoneyIntended(_funding) { checkCampaignExists(_id); CampaignManager.Campaign storage campaign = campaigns[_id]; campaign.fundCampaign(_funding); }
7,070,515
./full_match/40/0xd5dfA52343d2BEbc587D49ADc4fAD83154922445/sources/project_/contracts/IArcanaERC20.sol
Interface of the ERC20 standard as defined in the EIP./
interface IArcanaERC20 is IERC20 { function mint(address to, uint256 amount) external; pragma solidity ^0.8.2; }
9,550,366
./full_match/97/0xe75d306558b6F072Ad64323EACD0D2133e51aafD/sources/project:/contracts/TokenFactory/factories/MarketplaceFactory.sol
Creates an ERC1155 token by the caller with OPERATOR_ROLE. uri. salt. Emits a {CreatedERC1155} event indicating the token address./
function createERC1155Token(string memory uri, uint salt) external onlyRole(OPERATOR_ROLE) whenNotPaused nonReentrant { address beaconProxy = _deployProxy(_getERC1155Data(uri), salt, tokenTypes.ERC1155); ERC1155 token = ERC1155(address(beaconProxy)); emit CreatedERC1155(address(token)); token.transferOwnership(msg.sender); token.grantRole(token.DEFAULT_ADMIN_ROLE(), msg.sender); token.grantRole(token.UPDATER_ROLE(), msg.sender); token.grantRole(token.PAUSER_ROLE(), msg.sender); token.grantRole(token.MINTER_ROLE(), msg.sender); }
3,283,675
./full_match/4/0xf02eb75EC54deA39A16d6037C09456e39f9E7880/sources/ERC721.sol
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; }
764,748
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../ConverterVersion.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/IConverterAnchor.sol"; import "../../interfaces/IConverterUpgrader.sol"; import "../../../utility/MathEx.sol"; import "../../../utility/ContractRegistryClient.sol"; import "../../../utility/Time.sol"; import "../../../token/interfaces/IDSToken.sol"; import "../../../token/ReserveToken.sol"; import "../../../INetworkSettings.sol"; /** * @dev This contract is a specialized version of the converter, which is * optimized for a liquidity pool that has 2 reserves with 50%/50% weights. */ contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using MathEx for *; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 private constant MAX_UINT112 = 2**112 - 1; uint256 private constant MAX_UINT32 = 2**32 - 1; uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes; uint256 private _reserveBalances; uint256 private _reserveBalancesProduct; IReserveToken[] private _reserveTokens; mapping(IReserveToken => uint256) private _reserveIds; IConverterAnchor private _anchor; // converter anchor contract uint32 private _maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000 uint32 private _conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee // average rate details: // bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1 // bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1 // bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1 // where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1 uint256 private _averageRateInfo; /** * @dev triggered after liquidity is added * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityAdded( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev triggered after liquidity is removed * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityRemoved( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev initializes a new StandardPoolConverter instance * * @param anchor anchor governed by the converter * @param registry address of a contract registry contract * @param maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor anchor, IContractRegistry registry, uint32 maxConversionFee ) public ContractRegistryClient(registry) validAddress(address(anchor)) validConversionFee(maxConversionFee) { _anchor = anchor; _maxConversionFee = maxConversionFee; } // ensures that the converter is active modifier active() { _active(); _; } // error message binary size optimization function _active() private view { require(isActive(), "ERR_INACTIVE"); } // ensures that the converter is not active modifier inactive() { _inactive(); _; } // error message binary size optimization function _inactive() private view { require(!isActive(), "ERR_ACTIVE"); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IReserveToken reserveToken) { _validReserve(reserveToken); _; } // error message binary size optimization function _validReserve(IReserveToken reserveToken) private view { require(_reserveIds[reserveToken] != 0, "ERR_INVALID_RESERVE"); } // validates conversion fee modifier validConversionFee(uint32 fee) { _validConversionFee(fee); _; } // error message binary size optimization function _validConversionFee(uint32 fee) private pure { require(fee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE"); } // validates reserve weight modifier validReserveWeight(uint32 weight) { _validReserveWeight(weight); _; } // error message binary size optimization function _validReserveWeight(uint32 weight) private pure { require(weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public pure virtual override returns (uint16) { return 3; } /** * @dev checks whether or not the converter version is 28 or higher * * @return true, since the converter version is 28 or higher */ function isV28OrHigher() external pure returns (bool) { return true; } /** * @dev returns the converter anchor * * @return the converter anchor */ function anchor() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev returns the maximum conversion fee (in units of PPM) * * @return the maximum conversion fee (in units of PPM) */ function maxConversionFee() external view override returns (uint32) { return _maxConversionFee; } /** * @dev returns the current conversion fee (in units of PPM) * * @return the current conversion fee (in units of PPM) */ function conversionFee() external view override returns (uint32) { return _conversionFee; } /** * @dev returns the average rate info * * @return the average rate info */ function averageRateInfo() external view returns (uint256) { return _averageRateInfo; } /** * @dev deposits ether * can only be called if the converter has an ETH reserve */ receive() external payable override(IConverter) validReserve(ReserveToken.NATIVE_TOKEN_ADDRESS) {} /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public view virtual override returns (bool) { return _anchor.owner() == address(this); } /** * @dev transfers the anchor ownership * the new owner needs to accept the transfer * can only be called by the converter upgrader while the upgrader is the owner * note that prior to version 28, you should use 'transferAnchorOwnership' instead * * @param newOwner new token owner */ function transferAnchorOwnership(address newOwner) public override ownerOnly only(CONVERTER_UPGRADER) { _anchor.transferOwnership(newOwner); } /** * @dev accepts ownership of the anchor after an ownership transfer * most converters are also activated as soon as they accept the anchor ownership * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public virtual override ownerOnly { // verify the the converter has exactly two reserves require(_reserveTokens.length == 2, "ERR_INVALID_RESERVE_COUNT"); _anchor.acceptOwnership(); syncReserveBalances(0); emit Activation(converterType(), _anchor, true); } /** * @dev updates the current conversion fee * can only be called by the contract owner * * @param fee new conversion fee, represented in ppm */ function setConversionFee(uint32 fee) external override ownerOnly { require(fee <= _maxConversionFee, "ERR_INVALID_CONVERSION_FEE"); emit ConversionFeeUpdate(_conversionFee, fee); _conversionFee = fee; } /** * @dev transfers reserve balances to a new converter during an upgrade * can only be called by the converter upgraded which should be set at its owner * * @param newConverter address of the converter to receive the new amount */ function transferReservesOnUpgrade(address newConverter) external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { uint256 reserveCount = _reserveTokens.length; for (uint256 i = 0; i < reserveCount; ++i) { IReserveToken reserveToken = _reserveTokens[i]; reserveToken.safeTransfer(newConverter, reserveToken.balanceOf(address(this))); syncReserveBalance(reserveToken); } } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new converter after the upgrade */ function upgrade() external ownerOnly { IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER)); // trigger de-activation event emit Activation(converterType(), _anchor, false); transferOwnership(address(converterUpgrader)); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic */ function onUpgradeComplete() external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev returns the number of reserve tokens * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view override returns (uint16) { return uint16(_reserveTokens.length); } /** * @dev returns the array of reserve tokens * * @return array of reserve tokens */ function reserveTokens() external view override returns (IReserveToken[] memory) { return _reserveTokens; } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive * * @param token address of the reserve token * @param weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IReserveToken token, uint32 weight) external virtual override ownerOnly inactive validExternalAddress(address(token)) validReserveWeight(weight) { require(address(token) != address(_anchor) && _reserveIds[token] == 0, "ERR_INVALID_RESERVE"); require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); _reserveTokens.push(token); _reserveIds[token] = _reserveTokens.length; } /** * @dev returns the reserve's weight * added in version 28 * * @param reserveToken reserve token contract address * * @return reserve weight */ function reserveWeight(IReserveToken reserveToken) external view validReserve(reserveToken) returns (uint32) { return PPM_RESOLUTION / 2; } /** * @dev returns the balance of a given reserve token * * @param reserveToken reserve token contract address * * @return the balance of the given reserve token */ function reserveBalance(IReserveToken reserveToken) public view override returns (uint256) { uint256 reserveId = _reserveIds[reserveToken]; require(reserveId != 0, "ERR_INVALID_RESERVE"); return reserveBalance(reserveId); } /** * @dev returns the balances of both reserve tokens * * @return the balances of both reserve tokens */ function reserveBalances() public view returns (uint256, uint256) { return reserveBalances(1, 2); } /** * @dev syncs all stored reserve balances */ function syncReserveBalances() external { syncReserveBalances(0); } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet */ function processNetworkFees() external nonReentrant { (uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet * * @param value amount of ether to exclude from the ether reserve balance (if relevant) * * @return new reserve balances */ function processNetworkFees(uint256 value) private returns (uint256, uint256) { syncReserveBalances(value); (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); (ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); reserveBalance0 -= fee0; reserveBalance1 -= fee1; setReserveBalances(1, 2, reserveBalance0, reserveBalance1); _reserveTokens[0].safeTransfer(address(wallet), fee0); _reserveTokens[1].safeTransfer(address(wallet), fee1); return (reserveBalance0, reserveBalance1); } /** * @dev returns the reserve balances of the given reserve tokens minus their corresponding fees * * @param baseReserveTokens reserve tokens * * @return reserve balances minus their corresponding fees */ function baseReserveBalances(IReserveToken[] memory baseReserveTokens) private view returns (uint256[2] memory) { uint256 reserveId0 = _reserveIds[baseReserveTokens[0]]; uint256 reserveId1 = _reserveIds[baseReserveTokens[1]]; (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1); (, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); return [reserveBalance0 - fee0, reserveBalance1 - fee1]; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function convert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) external payable override nonReentrant only(BANCOR_NETWORK) returns (uint256) { require(sourceToken != targetToken, "ERR_SAME_SOURCE_TARGET"); return doConvert(sourceToken, targetToken, sourceAmount, trader, beneficiary); } /** * @dev returns the conversion fee for a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFee(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee) / PPM_RESOLUTION; } /** * @dev returns the conversion fee taken from a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFeeInv(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee).div(PPM_RESOLUTION - _conversionFee); } /** * @dev loads the stored reserve balance for a given reserve id * * @param reserveId reserve id */ function reserveBalance(uint256 reserveId) private view returns (uint256) { return decodeReserveBalance(_reserveBalances, reserveId); } /** * @dev loads the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id */ function reserveBalances(uint256 sourceId, uint256 targetId) private view returns (uint256, uint256) { require((sourceId == 1 && targetId == 2) || (sourceId == 2 && targetId == 1), "ERR_INVALID_RESERVES"); return decodeReserveBalances(_reserveBalances, sourceId, targetId); } /** * @dev stores the stored reserve balance for a given reserve id * * @param reserveId reserve id * @param balance reserve balance */ function setReserveBalance(uint256 reserveId, uint256 balance) private { require(balance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); uint256 otherBalance = decodeReserveBalance(_reserveBalances, 3 - reserveId); _reserveBalances = encodeReserveBalances(balance, reserveId, otherBalance, 3 - reserveId); } /** * @dev stores the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id * @param sourceBalance source reserve balance * @param targetBalance target reserve balance */ function setReserveBalances( uint256 sourceId, uint256 targetId, uint256 sourceBalance, uint256 targetBalance ) private { require(sourceBalance <= MAX_UINT128 && targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); _reserveBalances = encodeReserveBalances(sourceBalance, sourceId, targetBalance, targetId); } /** * @dev syncs the stored reserve balance for a given reserve with the real reserve balance * * @param reserveToken address of the reserve token */ function syncReserveBalance(IReserveToken reserveToken) private { uint256 reserveId = _reserveIds[reserveToken]; setReserveBalance(reserveId, reserveToken.balanceOf(address(this))); } /** * @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant) * * @param value amount of ether to exclude from the ether reserve balance (if relevant) */ function syncReserveBalances(uint256 value) private { IReserveToken _reserveToken0 = _reserveTokens[0]; IReserveToken _reserveToken1 = _reserveTokens[1]; uint256 balance0 = _reserveToken0.balanceOf(address(this)) - (_reserveToken0.isNativeToken() ? value : 0); uint256 balance1 = _reserveToken1.balanceOf(address(this)) - (_reserveToken1.isNativeToken() ? value : 0); setReserveBalances(1, 2, balance0, balance1); } /** * @dev helper, dispatches the Conversion event * * @param sourceToken source ERC20 token * @param targetToken target ERC20 token * @param trader address of the caller who executed the conversion * @param sourceAmount amount purchased/sold (in the source token) * @param targetAmount amount returned (in the target token) * @param feeAmount the fee amount */ function dispatchConversionEvent( IReserveToken sourceToken, IReserveToken targetToken, address trader, uint256 sourceAmount, uint256 targetAmount, uint256 feeAmount ) private { emit Conversion(sourceToken, targetToken, trader, sourceAmount, targetAmount, int256(feeAmount)); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) public view virtual override active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); return targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceBalance balance in the source reserve token contract * @param targetBalance balance in the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken, /* sourceToken */ IReserveToken, /* targetToken */ uint256 sourceBalance, uint256 targetBalance, uint256 sourceAmount ) private view returns (uint256, uint256) { uint256 targetAmount = crossReserveTargetAmount(sourceBalance, targetBalance, sourceAmount); uint256 fee = calculateFee(targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the required amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param targetAmount amount of target reserve tokens desired * * @return required amount in units of the source reserve token * @return expected fee in units of the target reserve token */ function sourceAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 targetAmount ) public view virtual active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); uint256 fee = calculateFeeInv(targetAmount); uint256 sourceAmount = crossReserveSourceAmount(sourceBalance, targetBalance, targetAmount.add(fee)); return (sourceAmount, fee); } /** * @dev converts a specific amount of source tokens to target tokens * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) private returns (uint256) { // update the recent average rate updateRecentAverageRate(); uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); // get the target amount minus the conversion fee and the conversion fee (uint256 targetAmount, uint256 fee) = targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance assert(targetAmount < targetBalance); // ensure that the input amount was already deposited uint256 actualSourceBalance = sourceToken.balanceOf(address(this)); if (sourceToken.isNativeToken()) { require(msg.value == sourceAmount, "ERR_ETH_AMOUNT_MISMATCH"); } else { require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= sourceAmount, "ERR_INVALID_AMOUNT"); } // sync the reserve balances setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - targetAmount); // transfer funds to the beneficiary in the to reserve token targetToken.safeTransfer(beneficiary, targetAmount); // dispatch the conversion event dispatchConversionEvent(sourceToken, targetToken, trader, sourceAmount, targetAmount, fee); // dispatch rate updates dispatchTokenRateUpdateEvents(sourceToken, targetToken, actualSourceBalance, targetBalance - targetAmount); return targetAmount; } /** * @dev returns the recent average rate of 1 token in the other reserve token units * * @param token token to get the rate for * * @return recent average rate between the reserves (numerator) * @return recent average rate between the reserves (denominator) */ function recentAverageRate(IReserveToken token) external view validReserve(token) returns (uint256, uint256) { // get the recent average rate of reserve 0 uint256 rate = calcRecentAverageRate(_averageRateInfo); uint256 rateN = decodeAverageRateN(rate); uint256 rateD = decodeAverageRateD(rate); if (token == _reserveTokens[0]) { return (rateN, rateD); } return (rateD, rateN); } /** * @dev updates the recent average rate if needed */ function updateRecentAverageRate() private { uint256 averageRateInfo1 = _averageRateInfo; uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1); if (averageRateInfo1 != averageRateInfo2) { _averageRateInfo = averageRateInfo2; } } /** * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units * * @param averageRateInfoData the average rate to use for the calculation * * @return recent average rate between the reserves */ function calcRecentAverageRate(uint256 averageRateInfoData) private view returns (uint256) { // get the previous average rate and its update-time uint256 prevAverageRateT = decodeAverageRateT(averageRateInfoData); uint256 prevAverageRateN = decodeAverageRateN(averageRateInfoData); uint256 prevAverageRateD = decodeAverageRateD(averageRateInfoData); // get the elapsed time since the previous average rate was calculated uint256 currentTime = time(); uint256 timeElapsed = currentTime - prevAverageRateT; // if the previous average rate was calculated in the current block, the average rate remains unchanged if (timeElapsed == 0) { return averageRateInfoData; } // get the current rate between the reserves (uint256 currentRateD, uint256 currentRateN) = reserveBalances(); // if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) { (currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, currentRateN, currentRateD); } uint256 x = prevAverageRateD.mul(currentRateN); uint256 y = prevAverageRateN.mul(currentRateD); // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath: uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed)); uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, newRateN, newRateD); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param reserves address of each reserve token * @param reserveAmounts amount of each reserve token * @param minReturn token minimum return-amount * * @return amount of pool tokens issued */ function addLiquidity( IReserveToken[] memory reserves, uint256[] memory reserveAmounts, uint256 minReturn ) external payable nonReentrant active returns (uint256) { // verify the user input verifyLiquidityInput(reserves, reserveAmounts, minReturn); // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH require( (!reserves[0].isNativeToken() || reserveAmounts[0] == msg.value) && (!reserves[1].isNativeToken() || reserveAmounts[1] == msg.value), "ERR_ETH_AMOUNT_MISMATCH" ); // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH if (msg.value > 0) { require(_reserveIds[ReserveToken.NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE"); } // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply uint256 totalSupply = poolToken.totalSupply(); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value); uint256 amount; uint256[2] memory newReserveAmounts; // calculate the amount of pool tokens to mint for the caller // and the amount of reserve tokens to transfer from the caller if (totalSupply == 0) { amount = MathEx.geometricMean(reserveAmounts); newReserveAmounts[0] = reserveAmounts[0]; newReserveAmounts[1] = reserveAmounts[1]; } else { (amount, newReserveAmounts) = addLiquidityAmounts( reserves, reserveAmounts, prevReserveBalances, totalSupply ); } uint256 newPoolTokenSupply = totalSupply.add(amount); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = newReserveAmounts[i]; require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= reserveAmounts[i]); // transfer each one of the reserve amounts from the user to the pool if (!reserveToken.isNativeToken()) { // ETH has already been transferred as part of the transaction reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount); } else if (reserveAmounts[i] > reserveAmount) { // transfer the extra amount of ETH back to the user reserveToken.safeTransfer(msg.sender, reserveAmounts[i] - reserveAmount); } // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount); emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; // verify that the equivalent amount of tokens is equal to or larger than the user's expectation require(amount >= minReturn, "ERR_RETURN_TOO_LOW"); // issue the tokens to the user poolToken.issue(msg.sender, amount); // return the amount of pool tokens issued return amount; } /** * @dev get the amount of pool tokens to mint for the caller * and the amount of reserve tokens to transfer from the caller * * @param amounts amount of each reserve token * @param balances balance of each reserve token * @param totalSupply total supply of pool tokens * * @return amount of pool tokens to mint for the caller * @return amount of reserve tokens to transfer from the caller */ function addLiquidityAmounts( IReserveToken[] memory, /* reserves */ uint256[] memory amounts, uint256[2] memory balances, uint256 totalSupply ) private pure returns (uint256, uint256[2] memory) { uint256 index = amounts[0].mul(balances[1]) < amounts[1].mul(balances[0]) ? 0 : 1; uint256 amount = fundSupplyAmount(totalSupply, balances[index], amounts[index]); uint256[2] memory newAmounts = [fundCost(totalSupply, balances[0], amount), fundCost(totalSupply, balances[1], amount)]; return (amount, newAmounts); } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param amount token amount * @param reserves address of each reserve token * @param minReturnAmounts minimum return-amount of each reserve token * * @return the amount of each reserve token granted for the given amount of pool tokens */ function removeLiquidity( uint256 amount, IReserveToken[] memory reserves, uint256[] memory minReturnAmounts ) external nonReentrant active returns (uint256[] memory) { // verify the user input bool inputRearranged = verifyLiquidityInput(reserves, minReturnAmounts, amount); // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply BEFORE destroying the user tokens uint256 totalSupply = poolToken.totalSupply(); // destroy the user tokens poolToken.destroy(msg.sender, amount); uint256 newPoolTokenSupply = totalSupply.sub(amount); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(amount, totalSupply, prevReserveBalances); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= minReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount); // transfer each one of the reserve amounts from the pool to the user reserveToken.safeTransfer(msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; if (inputRearranged) { uint256 tempReserveAmount = reserveAmounts[0]; reserveAmounts[0] = reserveAmounts[1]; reserveAmounts[1] = tempReserveAmount; } // return the amount of each reserve token granted for the given amount of pool tokens return reserveAmounts; } /** * @dev given the amount of one of the reserve tokens to add liquidity of, * returns the required amount of each one of the other reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param index index of the relevant reserve token * @param amount amount of the relevant reserve token * * @return the required amount of each one of the reserve tokens */ function addLiquidityCost( IReserveToken[] memory reserves, uint256 index, uint256 amount ) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); uint256 supplyAmount = fundSupplyAmount(totalSupply, baseBalances[index], amount); uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], supplyAmount); reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], supplyAmount); return reserveAmounts; } /** * @dev returns the amount of pool tokens entitled for given amounts of reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param amounts amount of each reserve token * * @return the amount of pool tokens entitled for the given amounts of reserve tokens */ function addLiquidityReturn(IReserveToken[] memory reserves, uint256[] memory amounts) external view returns (uint256) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); (uint256 amount, ) = addLiquidityAmounts(reserves, amounts, baseBalances, totalSupply); return amount; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param reserves address of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReturn(uint256 amount, IReserveToken[] memory reserves) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); return removeLiquidityReserveAmounts(amount, totalSupply, baseBalances); } /** * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens * we take this input in order to allow specifying the corresponding reserve amounts in any order * this function rearranges the input arrays according to the converter's array of reserve tokens * * @param reserves array of reserve tokens * @param amounts array of reserve amounts * @param amount token amount * * @return true if the function has rearranged the input arrays; false otherwise */ function verifyLiquidityInput( IReserveToken[] memory reserves, uint256[] memory amounts, uint256 amount ) private view returns (bool) { require(validReserveAmounts(amounts) && amount > 0, "ERR_ZERO_AMOUNT"); uint256 reserve0Id = _reserveIds[reserves[0]]; uint256 reserve1Id = _reserveIds[reserves[1]]; if (reserve0Id == 2 && reserve1Id == 1) { IReserveToken tempReserveToken = reserves[0]; reserves[0] = reserves[1]; reserves[1] = tempReserveToken; uint256 tempReserveAmount = amounts[0]; amounts[0] = amounts[1]; amounts[1] = tempReserveAmount; return true; } require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE"); return false; } /** * @dev checks whether or not both reserve amounts are larger than zero * * @param amounts array of reserve amounts * * @return true if both reserve amounts are larger than zero; false otherwise */ function validReserveAmounts(uint256[] memory amounts) private pure returns (bool) { return amounts[0] > 0 && amounts[1] > 0; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param totalSupply total supply of pool tokens * @param balances balance of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReserveAmounts( uint256 amount, uint256 totalSupply, uint256[2] memory balances ) private pure returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = liquidateReserveAmount(totalSupply, balances[0], amount); reserveAmounts[1] = liquidateReserveAmount(totalSupply, balances[1], amount); return reserveAmounts; } /** * @dev dispatches token rate update events for the reserve tokens and the pool token * * @param sourceToken address of the source reserve token * @param targetToken address of the target reserve token * @param sourceBalance balance of the source reserve token * @param targetBalance balance of the target reserve token */ function dispatchTokenRateUpdateEvents( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceBalance, uint256 targetBalance ) private { // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply of pool tokens uint256 poolTokenSupply = poolToken.totalSupply(); // dispatch token rate update event for the reserve tokens emit TokenRateUpdate(address(sourceToken), address(targetToken), targetBalance, sourceBalance); // dispatch token rate update events for the pool token emit TokenRateUpdate(address(poolToken), address(sourceToken), sourceBalance, poolTokenSupply); emit TokenRateUpdate(address(poolToken), address(targetToken), targetBalance, poolTokenSupply); } function encodeReserveBalance(uint256 balance, uint256 id) private pure returns (uint256) { assert(balance <= MAX_UINT128 && (id == 1 || id == 2)); return balance << ((id - 1) * 128); } function decodeReserveBalance(uint256 balances, uint256 id) private pure returns (uint256) { assert(id == 1 || id == 2); return (balances >> ((id - 1) * 128)) & MAX_UINT128; } function encodeReserveBalances( uint256 balance0, uint256 id0, uint256 balance1, uint256 id1 ) private pure returns (uint256) { return encodeReserveBalance(balance0, id0) | encodeReserveBalance(balance1, id1); } function decodeReserveBalances( uint256 _balances, uint256 id0, uint256 id1 ) private pure returns (uint256, uint256) { return (decodeReserveBalance(_balances, id0), decodeReserveBalance(_balances, id1)); } function encodeAverageRateInfo( uint256 averageRateT, uint256 averageRateN, uint256 averageRateD ) private pure returns (uint256) { assert(averageRateT <= MAX_UINT32 && averageRateN <= MAX_UINT112 && averageRateD <= MAX_UINT112); return (averageRateT << 224) | (averageRateN << 112) | averageRateD; } function decodeAverageRateT(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData >> 224; } function decodeAverageRateN(uint256 averageRateInfoData) private pure returns (uint256) { return (averageRateInfoData >> 112) & MAX_UINT112; } function decodeAverageRateD(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData & MAX_UINT112; } /** * @dev returns the largest integer smaller than or equal to the square root of a given value * * @param x the given value * * @return the largest integer smaller than or equal to the square root of the given value */ function floorSqrt(uint256 x) private pure returns (uint256) { return x > 0 ? MathEx.floorSqrt(x) : 0; } function crossReserveTargetAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 sourceAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0 && targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); return targetReserveBalance.mul(sourceAmount) / sourceReserveBalance.add(sourceAmount); } function crossReserveSourceAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 targetAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(targetAmount < targetReserveBalance, "ERR_INVALID_AMOUNT"); if (targetAmount == 0) { return 0; } return (sourceReserveBalance.mul(targetAmount) - 1) / (targetReserveBalance - targetAmount) + 1; } function fundCost( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return (amount.mul(balance) - 1) / supply + 1; } function fundSupplyAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return amount.mul(supply) / balance; } function liquidateReserveAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(amount <= supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (amount == 0) { return 0; } // special case for liquidating the entire supply if (amount == supply) { return balance; } return amount.mul(balance) / supply; } /** * @dev returns the network wallet and fees * * @param reserveBalance0 1st reserve balance * @param reserveBalance1 2nd reserve balance * * @return the network wallet * @return the network fee on the 1st reserve * @return the network fee on the 2nd reserve */ function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1) private view returns ( ITokenHolder, uint256, uint256 ) { uint256 prevPoint = floorSqrt(_reserveBalancesProduct); uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1); if (prevPoint >= currPoint) { return (ITokenHolder(address(0)), 0, 0); } (ITokenHolder networkFeeWallet, uint32 networkFee) = INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams(); uint256 n = (currPoint - prevPoint) * networkFee; uint256 d = currPoint * PPM_RESOLUTION; return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d)); } /** * @dev deprecated since version 28, backward compatibility - use only for earlier versions */ function token() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev deprecated, backward compatibility */ function transferTokenOwnership(address newOwner) external override ownerOnly { transferAnchorOwnership(newOwner); } /** * @dev deprecated, backward compatibility */ function acceptTokenOwnership() public override ownerOnly { acceptAnchorOwnership(); } /** * @dev deprecated, backward compatibility */ function connectors(IReserveToken reserveToken) external view override returns ( uint256, uint32, bool, bool, bool ) { uint256 reserveId = _reserveIds[reserveToken]; if (reserveId != 0) { return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true); } return (0, 0, false, false, false); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 index) external view override returns (IReserveToken) { return _reserveTokens[index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() external view override returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IReserveToken reserveToken) external view override returns (uint256) { return reserveBalance(reserveToken); } /** * @dev deprecated, backward compatibility */ function getReturn( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) external view returns (uint256, uint256) { return targetAmountAndFee(sourceToken, targetToken, sourceAmount); } }
helper, dispatches the Conversion event sourceToken source ERC20 token targetToken target ERC20 token trader address of the caller who executed the conversion sourceAmount amount purchased/sold (in the source token) targetAmount amount returned (in the target token) feeAmount the fee amount/
function dispatchConversionEvent( IReserveToken sourceToken, IReserveToken targetToken, address trader, uint256 sourceAmount, uint256 targetAmount, uint256 feeAmount ) private { emit Conversion(sourceToken, targetToken, trader, sourceAmount, targetAmount, int256(feeAmount)); }
12,547,179
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract TaskBlacklist is Ownable { /// @notice The blacklist of the tasks. mapping(bytes32 => bool) private _blacklistedTasks; event TaskBlacklistAdded(bytes32 taskId); event TaskBlacklistRemoved(bytes32 taskId); modifier onlyValidTask(bytes32 _taskId) { require(isValidTask(_taskId), "Invalid task"); _; } /// @notice Ban the task from being able to be executed. /// @param _taskId The task to be banned. function banTask(bytes32 _taskId) external onlyOwner { _blacklistedTasks[_taskId] = true; emit TaskBlacklistAdded(_taskId); } /// @notice Unban the task. /// @param _taskId The task to be unbanned. function unbanTask(bytes32 _taskId) external onlyOwner { require(!isValidTask(_taskId), "Not banned"); _blacklistedTasks[_taskId] = false; emit TaskBlacklistRemoved(_taskId); } /// @notice Return if the task is valid. /// @param _taskId The task to be queried. function isValidTask(bytes32 _taskId) public view returns (bool) { return (!_blacklistedTasks[_taskId]); } }
Ban the task from being able to be executed. _taskId The task to be banned.
function banTask(bytes32 _taskId) external onlyOwner { _blacklistedTasks[_taskId] = true; emit TaskBlacklistAdded(_taskId); }
12,843,596
./partial_match/1/0xAAcC51327ad63E22a63D8E1b2187716182D56dad/sources/src/test/MaliciousRecipient.sol
Also receive some eth in the process
function setStartAttack() public payable { startAttack = true; }
16,103,558
// Dependency file: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // Dependency file: contracts/libraries/Verifier.sol // pragma solidity >=0.8.4 <0.9.0; library Verifier { function verifySerialized(bytes memory message, bytes memory signature) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { // Singature need to be 65 in length // if (signature.length !== 65) revert(); if iszero(eq(mload(signature), 65)) { revert(0, 0) } // r = signature[:32] // s = signature[32:64] // v = signature[64] r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return verify(message, r, s, v); } function verify( bytes memory message, bytes32 r, bytes32 s, uint8 v ) public pure returns (address) { if (v < 27) { v += 27; } // V must be 27 or 28 require(v == 27 || v == 28, 'Invalid v value'); // Get hashes of message with Ethereum proof prefix bytes32 hashes = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n', uintToStr(message.length), message)); return ecrecover(hashes, v, r, s); } function uintToStr(uint256 value) public pure returns (string memory result) { // 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); } } // Dependency file: contracts/libraries/Bytes.sol // pragma solidity >=0.8.4 <0.9.0; library Bytes { // Convert bytes to bytes32[] function toBytes32Array(bytes memory input) public pure returns (bytes32[] memory) { require(input.length % 32 == 0, 'Bytes: invalid data length should divied by 32'); bytes32[] memory result = new bytes32[](input.length / 32); assembly { // Read length of data from offset let length := mload(input) // Seek offset to the beginning let offset := add(input, 0x20) // Next is size of chunk let resultOffset := add(result, 0x20) for { let i := 0 } lt(i, length) { i := add(i, 0x20) } { mstore(resultOffset, mload(add(offset, i))) resultOffset := add(resultOffset, 0x20) } } return result; } // Read address from input bytes buffer function readAddress(bytes memory input, uint256 offset) public pure returns (address result) { require(offset + 20 <= input.length, 'Bytes: Out of range, can not read address from bytes'); assembly { result := shr(96, mload(add(add(input, 0x20), offset))) } } // Read uint256 from input bytes buffer function readUint256(bytes memory input, uint256 offset) public pure returns (uint256 result) { require(offset + 32 <= input.length, 'Bytes: Out of range, can not read uint256 from bytes'); assembly { result := mload(add(add(input, 0x20), offset)) } } // Read bytes from input bytes buffer function readBytes( bytes memory input, uint256 offset, uint256 length ) public pure returns (bytes memory) { require(offset + length <= input.length, 'Bytes: Out of range, can not read bytes from bytes'); bytes memory result = new bytes(length); assembly { // Seek offset to the beginning let seek := add(add(input, 0x20), offset) // Next is size of data let resultOffset := add(result, 0x20) for { let i := 0 } lt(i, length) { i := add(i, 0x20) } { mstore(add(resultOffset, i), mload(add(seek, i))) } } return result; } } // Dependency file: contracts/operators/MultiOwner.sol // pragma solidity >=0.8.4 <0.9.0; contract MultiOwner { // Multi owner data mapping(address => bool) private _owners; // Multi owner data mapping(address => uint256) private _activeTime; // Total number of owners uint256 private _totalOwner; // Only allow listed address to trigger smart contract modifier onlyListedOwner() { require( _owners[msg.sender] && block.timestamp > _activeTime[msg.sender], 'MultiOwner: We are only allow owner to trigger this contract' ); _; } // Transfer ownership event event TransferOwnership(address indexed preOwner, address indexed newOwner); constructor(address[] memory owners_) { for (uint256 i = 0; i < owners_.length; i += 1) { _owners[owners_[i]] = true; emit TransferOwnership(address(0), owners_[i]); } _totalOwner = owners_.length; } /******************************************************* * Internal section ********************************************************/ function _transferOwnership(address newOwner, uint256 lockDuration) internal returns (bool) { require(newOwner != address(0), 'MultiOwner: Can not transfer ownership to zero address'); _owners[msg.sender] = false; _owners[newOwner] = true; _activeTime[newOwner] = block.timestamp + lockDuration; emit TransferOwnership(msg.sender, newOwner); return _owners[newOwner]; } /******************************************************* * View section ********************************************************/ function isOwner(address checkAddress) public view returns (bool) { return _owners[checkAddress] && block.timestamp > _activeTime[checkAddress]; } function totalOwner() public view returns (uint256) { return _totalOwner; } } // Root file: contracts/operators/MultiSig.sol pragma solidity >=0.8.4 <0.9.0; // import '/Users/chiro/GitHub/infrastructure/node_modules/@openzeppelin/contracts/utils/Address.sol'; // import 'contracts/libraries/Verifier.sol'; // import 'contracts/libraries/Bytes.sol'; // import 'contracts/operators/MultiOwner.sol'; /** * Multi Signature Wallet * Name: N/A * Domain: N/A */ contract MultiSig is MultiOwner { // Address lib providing safe {call} and {delegatecall} using Address for address; // Byte manipulation using Bytes for bytes; // Verifiy digital signature using Verifier for bytes; // Structure of proposal struct Proposal { int256 vote; uint64 expired; bool executed; bool delegate; uint256 value; address target; bytes data; } // Proposal index, begin from 1 uint256 private _proposalIndex; // Proposal storage mapping(uint256 => Proposal) private _proposalStorage; // Voted storage mapping(uint256 => mapping(address => bool)) private _votedStorage; // Quick transaction nonce uint256 private _nonce; // Create a new proposal event CreateProposal(uint256 indexed proposalId, uint256 indexed expired); // Execute proposal event ExecuteProposal(uint256 indexed proposalId, address indexed trigger, int256 indexed vote); // Positive vote event PositiveVote(uint256 indexed proposalId, address indexed owner); // Negative vote event NegativeVote(uint256 indexed proposalId, address indexed owner); // This contract able to receive fund receive() external payable {} // Pass parameters to parent contract constructor(address[] memory owners_) MultiOwner(owners_) {} /******************************************************* * Owner section ********************************************************/ // Transfer ownership to new owner function transferOwnership(address newOwner) external onlyListedOwner { // New owner will be activated after 3 days _transferOwnership(newOwner, 3 days); } // Transfer with signed proofs instead of onchain voting function quickTransfer(bytes[] memory signatures, bytes memory txData) external onlyListedOwner returns (bool) { uint256 totalSigned = 0; address[] memory signedAddresses = new address[](signatures.length); for (uint256 i = 0; i < signatures.length; i += 1) { address signer = txData.verifySerialized(signatures[i]); // Each signer only able to be counted once if (isOwner(signer) && _isNotInclude(signedAddresses, signer)) { signedAddresses[totalSigned] = signer; totalSigned += 1; } } require(_calculatePercent(int256(totalSigned)) >= 70, 'MultiSig: Total signed was not greater than 70%'); uint256 nonce = txData.readUint256(0); address target = txData.readAddress(32); bytes memory data = txData.readBytes(52, txData.length - 52); require(nonce - _nonce == 1, 'MultiSign: Invalid nonce value'); _nonce = nonce; target.functionCallWithValue(data, 0); return true; } // Create a new proposal function createProposal(Proposal memory newProposal) external onlyListedOwner returns (uint256) { _proposalIndex += 1; newProposal.expired = uint64(block.timestamp + 1 days); newProposal.vote = 0; _proposalStorage[_proposalIndex] = newProposal; emit CreateProposal(_proposalIndex, newProposal.expired); return _proposalIndex; } // Positive vote function votePositive(uint256 proposalId) external onlyListedOwner returns (bool) { return _voteProposal(proposalId, true); } // Negative vote function voteNegative(uint256 proposalId) external onlyListedOwner returns (bool) { return _voteProposal(proposalId, false); } // Execute a voted proposal function execute(uint256 proposalId) external onlyListedOwner returns (bool) { Proposal memory currentProposal = _proposalStorage[proposalId]; int256 positiveVoted = _calculatePercent(currentProposal.vote); // If positiveVoted < 70%, It need to pass 50% and expired if (positiveVoted < 70) { require(block.timestamp > _proposalStorage[proposalId].expired, "MultiSig: Voting period wasn't over"); require(positiveVoted >= 50, 'MultiSig: Vote was not pass 50%'); } require(currentProposal.executed == false, 'MultiSig: Proposal was executed'); if (currentProposal.delegate) { currentProposal.target.functionDelegateCall(currentProposal.data); } else { if (currentProposal.target.isContract()) { currentProposal.target.functionCallWithValue(currentProposal.data, currentProposal.value); } else { payable(address(currentProposal.target)).transfer(currentProposal.value); } } currentProposal.executed = true; _proposalStorage[proposalId] = currentProposal; emit ExecuteProposal(proposalId, msg.sender, currentProposal.vote); return true; } /******************************************************* * Private section ********************************************************/ // Vote a proposal function _voteProposal(uint256 proposalId, bool positive) private returns (bool) { require(block.timestamp < _proposalStorage[proposalId].expired, 'MultiSig: Voting period was over'); require(_votedStorage[proposalId][msg.sender] == false, 'MultiSig: You had voted this proposal'); if (positive) { _proposalStorage[proposalId].vote += 1; emit PositiveVote(proposalId, msg.sender); } else { _proposalStorage[proposalId].vote -= 1; emit NegativeVote(proposalId, msg.sender); } _votedStorage[proposalId][msg.sender] = true; return true; } /******************************************************* * Pure section ********************************************************/ function _isNotInclude(address[] memory addressList, address checkAddress) private pure returns (bool) { for (uint256 i = 0; i < addressList.length; i += 1) { if (addressList[i] == checkAddress) { return false; } } return true; } function _calculatePercent(int256 votedOwner) private view returns (int256) { return (votedOwner * 10000) / int256(totalOwner() * 100); } /******************************************************* * View section ********************************************************/ function proposalIndex() external view returns (uint256) { return _proposalIndex; } function proposalDetail(uint256 index) external view returns (Proposal memory) { return _proposalStorage[index]; } function isVoted(uint256 proposalId, address owner) external view returns (bool) { return _votedStorage[proposalId][owner]; } function getNextValidNonce() external view returns (uint256) { return _nonce + 1; } }
Execute a voted proposal If positiveVoted < 70%, It need to pass 50% and expired
function execute(uint256 proposalId) external onlyListedOwner returns (bool) { Proposal memory currentProposal = _proposalStorage[proposalId]; int256 positiveVoted = _calculatePercent(currentProposal.vote); if (positiveVoted < 70) { require(block.timestamp > _proposalStorage[proposalId].expired, "MultiSig: Voting period wasn't over"); require(positiveVoted >= 50, 'MultiSig: Vote was not pass 50%'); } require(currentProposal.executed == false, 'MultiSig: Proposal was executed'); if (currentProposal.delegate) { currentProposal.target.functionDelegateCall(currentProposal.data); if (currentProposal.target.isContract()) { currentProposal.target.functionCallWithValue(currentProposal.data, currentProposal.value); payable(address(currentProposal.target)).transfer(currentProposal.value); } } currentProposal.executed = true; _proposalStorage[proposalId] = currentProposal; emit ExecuteProposal(proposalId, msg.sender, currentProposal.vote); return true; }
6,437,687
// SPDX-License-Identifier: U-U-U-UPPPPP!!! pragma solidity ^0.7.4; import "./TokensRecoverable.sol"; import "./IERC31337.sol"; import "./IUniswapV2Router02.sol"; import "./IERC20.sol"; import "./RootedTransferGate.sol"; import "./IUniswapV2Factory.sol"; import "./SafeMath.sol"; import "./SafeERC20.sol"; import "./ILiquidityController.sol"; import "./IFloorCalculator.sol"; contract LiquidityController is TokensRecoverable, ILiquidityController { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Router02 immutable uniswapV2Router; IUniswapV2Factory immutable uniswapV2Factory; IERC20 immutable rooted; IERC20 immutable base; IERC20 immutable fiat; IERC31337 immutable elite; IERC20 immutable rootedEliteLP; IERC20 immutable rootedBaseLP; IERC20 immutable rootedFiatLP; IFloorCalculator public calculator; RootedTransferGate public gate; mapping(address => bool) public liquidityControllers; constructor(IUniswapV2Router02 _uniswapV2Router, IERC20 _base, IERC20 _rooted, IERC31337 _elite, IERC20 _fiat, IFloorCalculator _calculator, RootedTransferGate _gate) { uniswapV2Router = _uniswapV2Router; base = _base; elite = _elite; rooted = _rooted; fiat = _fiat; calculator = _calculator; gate = _gate; IUniswapV2Factory _uniswapV2Factory = IUniswapV2Factory(_uniswapV2Router.factory()); uniswapV2Factory = _uniswapV2Factory; _base.safeApprove(address(_uniswapV2Router), uint256(-1)); _base.safeApprove(address(_elite), uint256(-1)); _rooted.approve(address(_uniswapV2Router), uint256(-1)); IERC20 _rootedBaseLP = IERC20(_uniswapV2Factory.getPair(address(_base), address(_rooted))); _rootedBaseLP.approve(address(_uniswapV2Router), uint256(-1)); rootedBaseLP = _rootedBaseLP; _elite.approve(address(_uniswapV2Router), uint256(-1)); IERC20 _rootedEliteLP = IERC20(_uniswapV2Factory.getPair(address(_elite), address(_rooted))); _rootedEliteLP.approve(address(_uniswapV2Router), uint256(-1)); rootedEliteLP = _rootedEliteLP; _fiat.approve(address(_uniswapV2Router), uint256(-1)); IERC20 _rootedFiatLP = IERC20(_uniswapV2Factory.getPair(address(_fiat), address(_rooted))); _rootedFiatLP.approve(address(_uniswapV2Router), uint256(-1)); rootedFiatLP = _rootedFiatLP; } modifier liquidityControllerOnly() { require(liquidityControllers[msg.sender], "Not a Liquidity Controller"); _; } // Owner function to enable other contracts or addresses to use the Liquidity Controller function setLiquidityController(address controlAddress, bool controller) public ownerOnly() { liquidityControllers[controlAddress] = controller; } function setCalculatorAndGate(IFloorCalculator _calculator, RootedTransferGate _gate) public ownerOnly() { calculator = _calculator; gate = _gate; } // Use Base tokens held by this contract to buy from the Base Pool and sell in the Elite Pool function balancePriceBase(uint256 amount) public override liquidityControllerOnly() { amount = buyRootedToken(address(base), amount); amount = sellRootedToken(address(elite), amount); elite.withdrawTokens(amount); } // Use Base tokens held by this contract to buy from the Elite Pool and sell in the Base Pool function balancePriceElite(uint256 amount) public override liquidityControllerOnly() { elite.depositTokens(amount); amount = buyRootedToken(address(elite), amount); amount = sellRootedToken(address(base), amount); } // Removes liquidity, buys from either pool, sets a temporary dump tax function removeBuyAndTax(uint256 amount, address token, uint16 tax, uint256 time) public override liquidityControllerOnly() { gate.setUnrestricted(true); amount = removeLiq(token, amount); buyRootedToken(token, amount); gate.setDumpTax(tax, time); gate.setUnrestricted(false); } // Uses value in the controller to buy function buyAndTax(address token, uint256 amountToSpend, uint16 tax, uint256 time) public override liquidityControllerOnly() { buyRootedToken(token, amountToSpend); gate.setDumpTax(tax, time); } // Sweeps the Base token under the floor to this address function sweepFloor() public override liquidityControllerOnly() { elite.sweepFloor(address(this)); } // Move liquidity from Elite pool --->> Base pool function zapEliteToBase(uint256 liquidity) public override liquidityControllerOnly() { gate.setUnrestricted(true); liquidity = removeLiq(address(elite), liquidity); elite.withdrawTokens(liquidity); addLiq(address(base), liquidity); gate.setUnrestricted(false); } // Move liquidity from Base pool --->> Elite pool function zapBaseToElite(uint256 liquidity) public override liquidityControllerOnly() { gate.setUnrestricted(true); liquidity = removeLiq(address(base), liquidity); elite.depositTokens(liquidity); addLiq(address(elite), liquidity); gate.setUnrestricted(false); } function wrapToElite(uint256 baseAmount) public override liquidityControllerOnly() { elite.depositTokens(baseAmount); } function unwrapElite(uint256 eliteAmount) public override liquidityControllerOnly() { elite.withdrawTokens(eliteAmount); } function addLiquidity(address eliteOrBase, uint256 baseAmount) public override liquidityControllerOnly() { gate.setUnrestricted(true); addLiq(eliteOrBase, baseAmount); gate.setUnrestricted(false); } function removeLiquidity(address eliteOrBase, uint256 tokens) public override liquidityControllerOnly() { gate.setUnrestricted(true); removeLiq(eliteOrBase, tokens); gate.setUnrestricted(false); } function buyRooted(address token, uint256 amountToSpend) public override liquidityControllerOnly() { buyRootedToken(token, amountToSpend); } function sellRooted(address token, uint256 amountToSpend) public override liquidityControllerOnly() { sellRootedToken(token, amountToSpend); } function addLiq(address eliteOrBase, uint256 baseAmount) internal { uniswapV2Router.addLiquidity(address(eliteOrBase), address(rooted), baseAmount, rooted.balanceOf(address(this)), 0, 0, address(this), block.timestamp); } function removeLiq(address eliteOrBase, uint256 tokens) internal returns (uint256) { (tokens, ) = uniswapV2Router.removeLiquidity(address(eliteOrBase), address(rooted), tokens, 0, 0, address(this), block.timestamp); return tokens; } function buyRootedToken(address token, uint256 amountToSpend) internal returns (uint256) { uint256[] memory amounts = uniswapV2Router.swapExactTokensForTokens(amountToSpend, 0, buyPath(token), address(this), block.timestamp); amountToSpend = amounts[1]; return amountToSpend; } function sellRootedToken(address token, uint256 amountToSpend) internal returns (uint256) { uint256[] memory amounts = uniswapV2Router.swapExactTokensForTokens(amountToSpend, 0, sellPath(token), address(this), block.timestamp); amountToSpend = amounts[1]; return amountToSpend; } function buyPath(address token) internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = address(token); path[1] = address(rooted); return path; } function sellPath(address token) internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = address(rooted); path[1] = address(token); return path; } }
Sweeps the Base token under the floor to this address
function sweepFloor() public override liquidityControllerOnly() { elite.sweepFloor(address(this)); }
14,338,773
// contracts/GameItems.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface ExternalContract { function balanceOf(address owner) external view returns (uint256 balance); } contract JackpotRoyale_SE_HWS_R1 is ERC1155, Ownable { string private baseUri; // Pinata URL string public name; // Collection Name string public symbol; // Collection symbol address private externalContractAddress = 0xFdbb8329f5755c4cD0A1Ac172D8a4dF66969c1ef; // Collabrated contract address address private communityWalletAddress = 0xC416a17966FdD5023Fc00E4e0b79558416e7D531; // Community wallet address uint256 private _unitPrice = 0.015 ether; uint256 private maxSupply = 9999; uint256[] private mintedTokenIds; mapping(uint256 => address) private tokenOwner; enum MintingStatus { Start, Pause, Close } MintingStatus private CurrentMintingStatus; // Events event MintingStatusChange(MintingStatus status); event OnMintToken(uint256[] mintedTokens, uint256 contractBalance); event OnSendAward( uint256 firstPrize, uint256 secondPrize, uint256 thirdPrize, uint256 communityPrize ); // Modifiers modifier beforeMint(uint256[] memory _tokenIds) { require( tx.origin == msg.sender && !Address.isContract(msg.sender), "Not allow EOA!" ); require( externalContractBalance(msg.sender) > 0, "You are not eligible for mint" ); require( CurrentMintingStatus == MintingStatus.Start, "Minting not started yet!" ); require(_tokenIds.length > 0, "Token id's missing"); require( mintedTokenIds.length + _tokenIds.length <= maxSupply, string( abi.encodePacked( Strings.toString(maxSupply - mintedTokenIds.length), " Tokens left to be mint " ) ) ); bool _validTokenIds = true; bool _tokenNotMintedYet = true; uint256 _tokenId; for (uint256 index = 0; index < _tokenIds.length; ++index) { _tokenId = _tokenIds[index]; if (tokenOwner[_tokenId] != address(0)) { _tokenNotMintedYet = false; break; } if (_tokenId < 1 || _tokenId > maxSupply) { _validTokenIds = false; break; } } require( _validTokenIds, string( abi.encodePacked( Strings.toString(_tokenId), " is invalid token Id " ) ) ); require( _tokenNotMintedYet, string( abi.encodePacked( "Token Id ", Strings.toString(_tokenId), " is already minted" ) ) ); require( msg.value >= getUnitPrice() * _tokenIds.length, "Not enough ETH sent" ); _; } modifier beforeSendReward( uint256 _firstWinnerTokenId, uint256 _secondWinnerTokenId, uint256 _thirdWinnerTokenId ) { require( tx.origin == msg.sender && !Address.isContract(msg.sender), "Not allow EOA!" ); require( CurrentMintingStatus == MintingStatus.Close, "Kindly close the minting" ); require( ownerOf(_firstWinnerTokenId) != address(0), string( abi.encodePacked( "Token Id ", Strings.toString(_firstWinnerTokenId), " has no owner" ) ) ); require( ownerOf(_secondWinnerTokenId) != address(0), string( abi.encodePacked( "Token Id ", Strings.toString(_secondWinnerTokenId), " has no owner" ) ) ); require( ownerOf(_thirdWinnerTokenId) != address(0), string( abi.encodePacked( "Token Id ", Strings.toString(_thirdWinnerTokenId), " has no owner" ) ) ); _; } constructor( string memory _baseUri, string memory _name, string memory _symbol ) ERC1155(string(abi.encodePacked(_baseUri, "{id}.json"))) { name = _name; symbol = _symbol; baseUri = _baseUri; CurrentMintingStatus = MintingStatus.Pause; } function mintToken(uint256[] memory _tokenIds) public payable beforeMint(_tokenIds) { if (mintedTokenIds.length + _tokenIds.length == maxSupply) { CurrentMintingStatus = MintingStatus.Close; emit MintingStatusChange(CurrentMintingStatus); } for (uint256 index = 0; index < _tokenIds.length; ++index) { uint256 _tokenId = _tokenIds[index]; _mint(msg.sender, _tokenId, 1, ""); tokenOwner[_tokenId] = msg.sender; mintedTokenIds.push(_tokenId); } emit OnMintToken(mintedTokenIds, getContractBalance()); } // Set - Get external contract address function getExternalContractAddress() public view returns (address) { return externalContractAddress; } function setExternalContractAddress(address _address) public onlyOwner { externalContractAddress = _address; } // Balance of minter in external contract function externalContractBalance(address _address) public view returns (uint256) { return ExternalContract(externalContractAddress).balanceOf(_address); } // Contract Settings function getContractSetting() public view returns ( uint256 unitPrice, uint256 totalSupply, uint256 mintedCount, uint256 contractBalance, MintingStatus mintingStatus ) { return ( _unitPrice, maxSupply, getMintedCount(), getContractBalance(), CurrentMintingStatus ); } // Total token minted function getMintedCount() internal view returns (uint256) { return mintedTokenIds.length; } // Get contract balance function getContractBalance() internal view returns (uint256) { return address(this).balance; } // Owner of token id function ownerOf(uint256 _tokenId) public view returns (address) { require(_tokenId > 0 && _tokenId <= maxSupply, "Invalid token id"); return tokenOwner[_tokenId]; } // Get array of minted token ids function getMintedTokenIds() public view returns (uint256[] memory) { return mintedTokenIds; } // Token price function getUnitPrice() public view returns (uint256) { return _unitPrice; } // Start, stop and close MINTING function startMinting() public onlyOwner { require( CurrentMintingStatus != MintingStatus.Close, "Not allow to start minting" ); CurrentMintingStatus = MintingStatus.Start; emit MintingStatusChange(CurrentMintingStatus); } function pauseMinting() public onlyOwner { require( CurrentMintingStatus != MintingStatus.Close, "Not allow to pause minting" ); CurrentMintingStatus = MintingStatus.Pause; emit MintingStatusChange(CurrentMintingStatus); } function closeMinting() public onlyOwner { CurrentMintingStatus = MintingStatus.Close; emit MintingStatusChange(CurrentMintingStatus); } // Send Award To Winner function sendAward( uint256 _firstWinnerTokenId, uint256 _secondWinnerTokenId, uint256 _thirdWinnerTokenId ) public onlyOwner beforeSendReward( _firstWinnerTokenId, _secondWinnerTokenId, _thirdWinnerTokenId ) { uint256 balance = address(this).balance; uint256 firstWinnerPrize = (balance / 100) * 30; // 30% uint256 secondWinnerPrize = (balance / 100) * 15; // 15% uint256 thirdWinnerPrize = (balance / 100) * 5; // 05% uint256 communityPrize = balance - (firstWinnerPrize + secondWinnerPrize + thirdWinnerPrize); // 50% address firstWinner = ownerOf(_firstWinnerTokenId); address secondWinner = ownerOf(_secondWinnerTokenId); address thirdWinner = ownerOf(_thirdWinnerTokenId); payable(firstWinner).transfer(firstWinnerPrize); payable(secondWinner).transfer(secondWinnerPrize); payable(thirdWinner).transfer(thirdWinnerPrize); payable(communityWalletAddress).transfer(communityPrize); emit OnSendAward(firstWinnerPrize,secondWinnerPrize, thirdWinnerPrize, communityPrize); } // ERC1155 Override Methods // @ Override function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { super.safeTransferFrom(from, to, id, amount, data); tokenOwner[id] = to; } // @ Override function safeBatchTransferFrom( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) public virtual override { require(false, "Method not allowed"); } // @ Override function uri(uint256 _tokenId) public view override returns (string memory) { return string( abi.encodePacked(baseUri, Strings.toString(_tokenId), ".json") ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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) (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/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Get array of minted token ids
function getMintedTokenIds() public view returns (uint256[] memory) { return mintedTokenIds; }
10,378,797
./full_match/4/0x999B3AC9F446374F1D1779daf768b904586E812b/sources/TimelockController.sol
Cancel an operation. Requirements: - the caller must have the 'canceller' role./
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); }
827,926
./partial_match/1/0xA83Bb332564e226779963bF0cD7c8ED4aAE40E95/sources/DarkMaster.sol
Handover the Darktoken mintage right.
function handoverDarkMintage(address newOwner) public onlyOwner { dark.transferOwnership(newOwner); }
16,049,406
./full_match/1/0x8D8912E1237F9FF3EF661F32743CFB276E052F98/sources/redpacket.sol
It takes the unhashed password and a hashed random seed generated from the user Unsuccessful
function claim(bytes32 id, string memory password, address payable recipient, bytes32 validation) public returns (uint claimed) { RedPacket storage rp = redpacket_by_id[id]; Packed memory packed = rp.packed; require (unbox(packed.packed1, 224, 32) > block.timestamp, "Expired"); uint total_number = unbox(packed.packed2, 239, 15); uint claimed_number = unbox(packed.packed2, 224, 15); require (claimed_number < total_number, "Out of stock"); require (uint256(keccak256(bytes(password))) >> 128 == unbox(packed.packed1, 0, 128), "Wrong password"); require (validation == keccak256(abi.encodePacked(msg.sender)), "Validation failed"); uint256 claimed_tokens; uint256 token_type = unbox(packed.packed2, 254, 1); uint256 ifrandom = unbox(packed.packed2, 255, 1); uint256 remaining_tokens = unbox(packed.packed1, 128, 96); if (ifrandom == 1) { if (total_number - claimed_number == 1) claimed_tokens = remaining_tokens; else claimed_tokens = random(seed, nonce) % SafeMath.div(SafeMath.mul(remaining_tokens, 2), total_number - claimed_number); if (claimed_tokens == 0) claimed_tokens = 1; if (total_number - claimed_number == 1) claimed_tokens = remaining_tokens; else claimed_tokens = SafeMath.div(remaining_tokens, (total_number - claimed_number)); } rp.packed.packed1 = rewriteBox(packed.packed1, 128, 96, remaining_tokens - claimed_tokens); rp.claimed_list[msg.sender] = claimed_tokens; rp.packed.packed2 = rewriteBox(packed.packed2, 224, 15, claimed_number + 1); recipient.transfer(claimed_tokens); else if (token_type == 1) transfer_token(address(uint160(unbox(packed.packed2, 0, 160))), address(this), recipient, claimed_tokens); return claimed_tokens; }
8,467,675
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.21; /// @title Utility Functions for address /// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a2a6a7aea5a0a8a7ae89a5a6a6b9bba0a7aee7a6bbae">[email&#160;protected]</a>> library StringUtil { function stringToBytes12(string str) internal pure returns (bytes12 result) { assembly { result := mload(add(str, 32)) } } function stringToBytes10(string str) internal pure returns (bytes10 result) { assembly { result := mload(add(str, 32)) } } /// check length >= min && <= max function checkStringLength(string name, uint min, uint max) internal pure returns (bool) { bytes memory temp = bytes(name); return temp.length >= min && temp.length <= max; } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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 Utility Functions for address /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284c4946414d4468444747585a41464f06475a4f">[email&#160;protected]</a>> library AddressUtil { function isContract( address addr ) internal view returns (bool) { if (addr == 0x0) { return false; } else { uint size; assembly { size := extcodesize(addr) } return size > 0; } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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 2017 Loopring Project Ltd (Loopring Foundation). 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 2017 Loopring Project Ltd (Loopring Foundation). 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 ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0b0e01060a032f0300001f1d06010841001d08">[email&#160;protected]</a>> contract ERC20 { function balanceOf( address who ) view public returns (uint256); function allowance( address owner, address spender ) view public returns (uint256); function transfer( address to, uint256 value ) public returns (bool); function transferFrom( address from, address to, uint256 value ) public returns (bool); function approve( address spender, uint256 value ) public returns (bool); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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 Utility Functions for uint /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a7e7b74737f765a7675756a6873747d3475687d">[email&#160;protected]</a>> library MathUint { function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a); } function tolerantSub( uint a, uint b ) internal pure returns (uint c) { return (a >= b) ? a - b : 0; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal pure returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg += arr[i]; } avg = avg / len; if (avg == 0) { return 0; } uint cvs = 0; uint s; uint item; for (i = 0; i < len; i++) { item = arr[i]; s = item > avg ? item - avg : avg - item; cvs += mul(s, s); } return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1); } } /// @title ERC20 Token Implementation /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0367626d6a666f436f6c6c73716a6d642d6c7164">[email&#160;protected]</a>> contract ERC20Token is ERC20 { using MathUint for uint; string public name; string public symbol; uint8 public decimals; uint public totalSupply_; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function ERC20Token( string _name, string _symbol, uint8 _decimals, uint _totalSupply, address _firstHolder ) public { require(_totalSupply > 0); require(_firstHolder != 0x0); checkSymbolAndName(_symbol,_name); name = _name; symbol = _symbol; decimals = _decimals; totalSupply_ = _totalSupply; balances[_firstHolder] = totalSupply_; } function () payable public { revert(); } /** * @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); 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]; } /** * @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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve( address _spender, 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; } // Make sure symbol has 3-8 chars in [A-Za-z._] and name has up to 128 chars. function checkSymbolAndName( string memory _symbol, string memory _name ) internal pure { bytes memory s = bytes(_symbol); require(s.length >= 3 && s.length <= 8); for (uint i = 0; i < s.length; i++) { require( s[i] == 0x2E || // "." s[i] == 0x5F || // "_" s[i] >= 0x41 && s[i] <= 0x5A || // [A-Z] s[i] >= 0x61 && s[i] <= 0x7A // [a-z] ); } bytes memory n = bytes(_name); require(n.length >= s.length && n.length <= 128); for (i = 0; i < n.length; i++) { require(n[i] >= 0x20 && n[i] <= 0x7E); } } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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 ERC20 Token Mint /// @dev This contract deploys ERC20 token contract and registered the contract /// so the token can be traded with Loopring Protocol. /// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583337363f343139363f18343737282a31363f76372a3f">[email&#160;protected]</a>>, /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0367626d6a666f436f6c6c73716a6d642d6c7164">[email&#160;protected]</a>>. contract TokenFactory { event TokenCreated( address indexed addr, string name, string symbol, uint8 decimals, uint totalSupply, address firstHolder ); /// @dev Deploy an ERC20 token contract, register it with TokenRegistry, /// and returns the new token&#39;s address. /// @param name The name of the token /// @param symbol The symbol of the token. /// @param decimals The decimals of the token. /// @param totalSupply The total supply of the token. function createToken( string name, string symbol, uint8 decimals, uint totalSupply ) external returns (address addr); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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 Token Register Contract /// @dev This contract maintains a list of tokens the Protocol supports. /// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="214a4e4f464d48404f46614d4e4e5153484f460f4e5346">[email&#160;protected]</a>>, /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a5a0afa8a4ad81adaeaeb1b3a8afa6efaeb3a6">[email&#160;protected]</a>>. contract TokenRegistry { event TokenRegistered(address addr, string symbol); event TokenUnregistered(address addr, string symbol); function registerToken( address addr, string symbol ) external; function registerMintedToken( address addr, string symbol ) external; function unregisterToken( address addr, string symbol ) external; function areAllTokensRegistered( address[] addressList ) external view returns (bool); function getAddressBySymbol( string symbol ) external view returns (address); function isTokenRegisteredBySymbol( string symbol ) public view returns (bool); function isTokenRegistered( address addr ) public view returns (bool); function getTokens( uint start, uint count ) public view returns (address[] addressList); } /// @title An Implementation of TokenFactory. /// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4dfdbdad3d8ddd5dad3f4d8dbdbc4c6dddad39adbc6d3">[email&#160;protected]</a>>, /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7115101f18141d311d1e1e0103181f165f1e0316">[email&#160;protected]</a>>. contract TokenFactoryImpl is TokenFactory { using AddressUtil for address; using StringUtil for string; mapping(bytes10 => address) public tokens; address public tokenRegistry; address public tokenTransferDelegate; /// @dev Disable default function. function () payable public { revert(); } function TokenFactoryImpl( address _tokenRegistry ) public { require(tokenRegistry == 0x0 && _tokenRegistry.isContract()); tokenRegistry = _tokenRegistry; } function createToken( string name, string symbol, uint8 decimals, uint totalSupply ) external returns (address addr) { require(tokenRegistry != 0x0); require(tokenTransferDelegate != 0x0); require(symbol.checkStringLength(3, 10)); bytes10 symbolBytes = symbol.stringToBytes10(); require(tokens[symbolBytes] == 0x0); ERC20Token token = new ERC20Token( name, symbol, decimals, totalSupply, tx.origin ); addr = address(token); TokenRegistry(tokenRegistry).registerMintedToken(addr, symbol); tokens[symbolBytes] = addr; emit TokenCreated( addr, name, symbol, decimals, totalSupply, tx.origin ); } }
Make sure symbol has 3-8 chars in [A-Za-z._] and name has up to 128 chars.
function checkSymbolAndName( string memory _symbol, string memory _name ) internal pure { bytes memory s = bytes(_symbol); require(s.length >= 3 && s.length <= 8); for (uint i = 0; i < s.length; i++) { require( ); } bytes memory n = bytes(_name); require(n.length >= s.length && n.length <= 128); for (i = 0; i < n.length; i++) { require(n[i] >= 0x20 && n[i] <= 0x7E); } }
2,246,193
./full_match/1/0x197CFa4C1275130699de3137E91a6d4e5A3Edd21/sources/scripts/contracts/Ownable.sol
Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./
function transferOwnership(address newOwner) public onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
4,879,191
//Address: 0xA5d1e58ECe1fC438d64E65769d2ab730143a4Caf //Contract name: RobomedIco //Balance: 555.251988902432127803 Ether //Verification Date: 10/24/2017 //Transacion Count: 1252 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title Math * @dev Assorted math operations y */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant public 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) constant public returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC223 { uint public totalSupply; function balanceOf(address who) constant public returns (uint); function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { string public functionName; address public sender; uint public value; bytes public data; function tokenFallback(address _from, uint _value, bytes _data) public { sender = _from; value = _value; data = _data; functionName = "tokenFallback"; //uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); //tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } function customFallback(address _from, uint _value, bytes _data) public { tokenFallback(_from, _value, _data); functionName = "customFallback"; } } contract RobomedIco is ERC223, ERC20 { using SafeMath for uint256; string public name = "RobomedToken"; string public symbol = "RBM"; uint8 public decimals = 18; //addresses /* * ADDR_OWNER - ะฒะปะฐะดะตะปะตั† ะบะพะฝั‚ั€ะฐะบั‚ะฐ - ั€ะฐัะฟั€ะตะดะตะปัะตั‚ ะฒะธะฟ ั‚ะพะบะตะฝั‹, ะฝะฐั‡ะธัะปัะตั‚ ะฑะฐัƒะฝั‚ะธ ะธ team, ะพััƒั‰ะตัั‚ะฒะปัะตั‚ ะฟะตั€ะตั…ะพะด ะฟะพ ัั‚ะฐะดะธัะผ */ address public constant ADDR_OWNER = 0x21F6C4D926B705aD244Ec33271559dA8c562400F; /* * ADDR_WITHDRAWAL1, ADDR_WITHDRAWAL2 - ัƒั‡ะฐัั‚ะฝะธะบะธ ะบะพะฝั‚ั€ะฐะบั‚ะฐ, ะบะพั‚ะพั€ั‹ะต ัะพะฒะผะตัั‚ะฝะพ ะฒั‹ะฒะพะดัั‚ eth ะฟะพัะปะต ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco */ address public constant ADDR_WITHDRAWAL1 = 0x0dD97e6259a7de196461B36B028456a97e3268bE; /* * ADDR_WITHDRAWAL1, ADDR_WITHDRAWAL2 - ัƒั‡ะฐัั‚ะฝะธะบะธ ะบะพะฝั‚ั€ะฐะบั‚ะฐ, ะบะพั‚ะพั€ั‹ะต ัะพะฒะผะตัั‚ะฝะพ ะฒั‹ะฒะพะดัั‚ eth ะฟะพัะปะต ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco */ address public constant ADDR_WITHDRAWAL2 = 0x8c5B02144F7664D37FDfd4a2f90148d08A04838D; /** * ะะดั€ะตั ะฝะฐ ะบะพั‚ะพั€ั‹ะน ะบะปะฐะดัƒั‚ัŒัั ั‚ะพะบะตะฝั‹ ะดะปั ั€ะฐะทะดะฐั‡ะธ ะฟะพ Baunty */ address public constant ADDR_BOUNTY_TOKENS_ACCOUNT = 0x6542393623Db0D7F27fDEd83e6feDBD767BfF9b4; /** * ะะดั€ะตั ะฝะฐ ะบะพั‚ะพั€ั‹ะน ะบะปะฐะดัƒั‚ัŒัั ั‚ะพะบะตะฝั‹ ะดะปั ั€ะฐะทะดะฐั‡ะธ Team */ address public constant ADDR_TEAM_TOKENS_ACCOUNT = 0x28c6bCAB2204CEd29677fEE6607E872E3c40d783; //VipPlacement constants /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ VipPlacement */ uint256 public constant INITIAL_COINS_FOR_VIPPLACEMENT =507937500 * 10 ** 18; /** * ะ”ะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ัั‚ะฐะดะธะธ VipPlacement */ uint256 public constant DURATION_VIPPLACEMENT = 1 seconds;// 1 minutes;// 1 days; //end VipPlacement constants //PreSale constants /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ PreSale */ uint256 public constant EMISSION_FOR_PRESALE = 76212500 * 10 ** 18; /** * ะ”ะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ัั‚ะฐะดะธะธ PreSale */ uint256 public constant DURATION_PRESALE = 1 days;//2 minutes;//1 days; /** * ะšัƒั€ั ัั‚ะฐะดะธะธ PreSale */ uint256 public constant RATE_PRESALE = 2702; //end PreSale constants //SaleStage1 constants /** * ะžะฑั‰ะฐั ะดะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ัั‚ะฐะดะธะน Sale ั SaleStage1 ะฟะพ SaleStage7 ะฒะบะปัŽั‡ะธั‚ะตะปัŒะฝะพ */ uint256 public constant DURATION_SALESTAGES = 10 days; //2 minutes;//30 days; /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage1 */ uint256 public constant RATE_SALESTAGE1 = 2536; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage1 */ uint256 public constant EMISSION_FOR_SALESTAGE1 = 40835000 * 10 ** 18; //end SaleStage1 constants //SaleStage2 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage2 */ uint256 public constant RATE_SALESTAGE2 = 2473; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage2 */ uint256 public constant EMISSION_FOR_SALESTAGE2 = 40835000 * 10 ** 18; //end SaleStage2 constants //SaleStage3 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage3 */ uint256 public constant RATE_SALESTAGE3 = 2390; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage3 */ uint256 public constant EMISSION_FOR_SALESTAGE3 = 40835000 * 10 ** 18; //end SaleStage3 constants //SaleStage4 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage4 */ uint256 public constant RATE_SALESTAGE4 = 2349; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage4 */ uint256 public constant EMISSION_FOR_SALESTAGE4 = 40835000 * 10 ** 18; //end SaleStage4 constants //SaleStage5 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage5 */ uint256 public constant RATE_SALESTAGE5 = 2286; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage5 */ uint256 public constant EMISSION_FOR_SALESTAGE5 = 40835000 * 10 ** 18; //end SaleStage5 constants //SaleStage6 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage6 */ uint256 public constant RATE_SALESTAGE6 = 2224; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage6 */ uint256 public constant EMISSION_FOR_SALESTAGE6 = 40835000 * 10 ** 18; //end SaleStage6 constants //SaleStage7 constants /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStage7 */ uint256 public constant RATE_SALESTAGE7 = 2182; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStage7 */ uint256 public constant EMISSION_FOR_SALESTAGE7 = 40835000 * 10 ** 18; //end SaleStage7 constants //SaleStageLast constants /** * ะ”ะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ัั‚ะฐะดะธะธ SaleStageLast */ uint256 public constant DURATION_SALESTAGELAST = 1 days;// 20 minutes;//10 days; /** * ะšัƒั€ั ัั‚ะฐะดะธะธ SaleStageLast */ uint256 public constant RATE_SALESTAGELAST = 2078; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั ัั‚ะฐะดะธะธ SaleStageLast */ uint256 public constant EMISSION_FOR_SALESTAGELAST = 302505000 * 10 ** 18; //end SaleStageLast constants //PostIco constants /** * ะ”ะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ะฟะตั€ะธะพะดะฐ ะฝะฐ ะบะพั‚ะพั€ั‹ะน ะฝะตะปัŒะทั ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ team ั‚ะพะบะตะฝั‹, ะฟะพะปัƒั‡ะตะฝะฝั‹ะต ะฟั€ะธ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะธ */ uint256 public constant DURATION_NONUSETEAM = 180 days;//10 days; /** * ะ”ะปะธั‚ะตะปัŒะฝะพัั‚ัŒ ะฟะตั€ะธะพะดะฐ ะฝะฐ ะบะพั‚ะพั€ั‹ะน ะฝะตะปัŒะทั ะฒะพััั‚ะฐะฝะพะฒะธั‚ัŒ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ะต unsoldTokens ั‚ะพะบะตะฝั‹, * ะพั‚ัั‡ะธั‚ั‹ะฒะฐะตั‚ัั ะฟะพัะปะต ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco */ uint256 public constant DURATION_BEFORE_RESTORE_UNSOLD = 270 days; //end PostIco constants /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั BOUNTY */ uint256 public constant EMISSION_FOR_BOUNTY = 83750000 * 10 ** 18; /** * ะญะผะธััะธั ั‚ะพะบะตะฝะพะฒ ะดะปั TEAM */ uint256 public constant EMISSION_FOR_TEAM = 418750000 * 10 ** 18; /** * ะšะพะป-ะฒะพ ั‚ะพะบะตะฝะพะฒ, ะบะพั‚ะพั€ะพะต ะฑัƒะดะตั‚ ะฝะฐั‡ะธัะปะตะฝะพ ะบะฐะถะดะพะผัƒ ัƒั‡ะฐัั‚ะฝะธะบัƒ ะบะพะผะฐะฝะดั‹ */ uint256 public constant TEAM_MEMBER_VAL = 2000000 * 10 ** 18; /** * ะŸะตั€ะตั‡ะธัะปะตะฝะธะต ัะพัั‚ะพัะฝะธะน ะบะพะฝั‚ั€ะฐะบั‚ะฐ */ enum IcoStates { /** * ะกะพัั‚ะพัะฝะธะต ะดะปั ะบะพั‚ะพั€ะพะณะพ ะฒั‹ะฟะพะปะฝัะตั‚ัั ะทะฐะดะฐะฝะฝะฐั ัะผะธััะธั ะฝะฐ ะบะพัˆะตะปั‘ะบ ะฒะปะฐะดะตะปัŒั†ะฐ, * ะดะฐะปะตะต ะฒัะต ะฒั‹ะฟัƒั‰ะตะฝะฝั‹ะต ั‚ะพะบะตะฝั‹ ั€ะฐัะฟั€ะตะดะตะปััŽั‚ัั ะฒะปะฐะดะตะปัŒั†ะตะผ ะธะท ัะฒะพะตะณะพ ะบะพัˆะตะปัŒะบะฐ ะฝะฐ ะฟั€ะพะธะทะฒะพะปัŒะฝั‹ะต ะบะพัˆะตะปัŒะบะธ, ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะต ะผะพะถะตั‚ ะฟั€ะพะธัั…ะพะดะธั‚ัŒ ะฒัะตะณะดะฐ. * ะ’ะปะฐะดะตะปะตั† ะฝะต ะผะพะถะตั‚ ั€ะฐัะฟั€ะตะดะตะปะธั‚ัŒ ะธะท ัะฒะพะตะณะพ ะบะพัˆะตะปัŒะบะฐ, ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะตะฒั‹ัˆะฐัŽั‰ะตะต INITIAL_COINS_FOR_VIPPLACEMENT ะดะพ ะฟั€ะตะบั€ะฐั‰ะตะฝะธั ICO * ะกะพัั‚ะพัะฝะธะต ะทะฐะฒะตั€ัˆะฐะตั‚ัั ะฟะพ ะฝะฐัั‚ัƒะฟะปะตะฝะธัŽ ะฒั€ะตะผะตะฝะธ endDateOfVipPlacement */ VipPlacement, /** * ะกะพัั‚ะพัะฝะธะต ะดะปั ะบะพั‚ะพั€ะพะณะพ ะฒั‹ะฟะพะปะฝัะตั‚ัั ะทะฐะดะฐะฝะฝะฐั ัะผะธััะธั ะฒ ัะฒะพะฑะพะดะฝั‹ะน ะฟัƒะป freeMoney. * ะดะฐะปะตะต ะฒัะต ะฒั‹ะฟัƒั‰ะตะฝะฝั‹ะต ัะฒะพะฑะพะดะฝั‹ะต ั‚ะพะบะตะฝั‹ ะฟะพะบัƒะฟะฐัŽั‚ัั ะฒัะตะผะธ ะถะตะปะฐัŽั‰ะธะผะธ ะฒะฟะปะพั‚ัŒ ะดะพ endDateOfPreSale, * ะฝะต ะฒั‹ะบัƒะฟะปะตะฝะฝั‹ะต ั‚ะพะบะตะฝั‹ ะฑัƒะดัƒั‚ ัƒะฝะธั‡ั‚ะพะถะตะฝั‹ * ะกะพัั‚ะพัะฝะธะต ะทะฐะฒะตั€ัˆะฐะตั‚ัั ะฟะพ ะฝะฐัั‚ัƒะฟะปะตะฝะธัŽ ะฒั€ะตะผะตะฝะธ endDateOfPreSale. * ะก ะผะพะผะตะฝั‚ะฐ ะฝะฐัั‚ัƒะฟะปะตะฝะธั PreSale ะฟะพะบัƒะฟะบะฐ ั‚ะพะบะตะฝะพะฒ ัั‚ะฐะฝะพะฒะธั‚ัŒัั ั€ะฐะทั€ะตัˆะตะฝะฐ */ PreSale, /** * ะกะพัั‚ะพัะฝะธะต ะฟั€ะตะดัั‚ะฐะฒะปััŽั‰ะตะต ะธะท ัะตะฑั ะฟะพะดัั‚ะฐะดะธัŽ ะฟั€ะพะดะฐะถ, * ะฟั€ะธ ะฝะฐัั‚ัƒะฟะปะตะฝะธะธ ะดะฐะฝะฝะพะณะพ ัะพัั‚ะพัะฝะธั ะฒั‹ะฟัƒัะบะฐะตั‚ัั ะทะฐะดะฐะฝะฝะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ, * ะบะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฟั€ะธั€ะฐะฒะฝะธะฒะฐะตั‚ัั ะบ ัั‚ะพะน ัะผะธััะธะธ * ะกะพัั‚ะพัะฝะธะต ะทะฐะฒะตั€ัˆะฐะตั‚ัั ะฟั€ะธ ะฒั‹ะบัƒะฟะต ะฒัะตั… ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะธะปะธ ะฟะพ ะฝะฐัั‚ัƒะฟะปะตะฝะธัŽ ะฒั€ะตะผะตะฝะธ startDateOfSaleStageLast. * ะ•ัะปะธ ะฒั‹ะบัƒะฟะฐัŽั‚ัั ะฒัะต ัะฒะพะฑะพะดะฝั‹ะต ั‚ะพะบะตะฝั‹ - ะฟะตั€ะตั…ะพะด ะพััƒั‰ะตัั‚ะฒะปัะตั‚ัั ะฝะฐ ัะปะตะดัƒัŽั‰ัƒัŽ ัั‚ะฐะดะธัŽ - * ะฝะฐะฟั€ะธะผะตั€ [ั SaleStage1 ะฝะฐ SaleStage2] ะธะปะธ [ั SaleStage2 ะฝะฐ SaleStage3] * ะ•ัะปะธ ะฝะฐัั‚ัƒะฟะฐะตั‚ ะฒั€ะตะผั startDateOfSaleStageLast, ั‚ะพ ะฝะตะทะฐะฒะธัะธะผะพ ะพั‚ ะฒั‹ะบัƒะฟะปะตะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฟะตั€ะตั…ะพะดะธะผ ะฝะฐ ัั‚ะพัั‚ะพัะฝะธะต SaleStageLast */ SaleStage1, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage2, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage3, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage4, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage5, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage6, /** * ะะฝะฐะปะพะณะธั‡ะฝะพ SaleStage1 */ SaleStage7, /** * ะกะพัั‚ะพัะฝะธะต ะฟั€ะตะดัั‚ะฐะฒะปััŽั‰ะตะต ะธะท ัะตะฑั ะฟะพัะปะตะดะฝัŽัŽ ะฟะพะดัั‚ะฐะดะธัŽ ะฟั€ะพะดะฐะถ, * ะฟั€ะธ ะฝะฐัั‚ัƒะฟะปะตะฝะธะธ ะดะฐะฝะฝะพะณะพ ัะพัั‚ะพัะฝะธั ะฒั‹ะฟัƒัะบะฐะตั‚ัั ะทะฐะดะฐะฝะฝะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ, * ะบะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฟั€ะธั€ะฐะฒะฝะธะฒะฐะตั‚ัั ะบ ัั‚ะพะน ัะผะธััะธะธ, * ะฟะปัŽั ะพัั‚ะฐั‚ะบะธ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ัะพ ัั‚ะฐะดะธะน SaleStage1,SaleStage2,SaleStage3,SaleStage4,SaleStage5,SaleStage6,SaleStage7 * ะกะพัั‚ะพัะฝะธะต ะทะฐะฒะตั€ัˆะฐะตั‚ัั ะฟะพ ะฝะฐัั‚ัƒะฟะปะตะฝะธัŽ ะฒั€ะตะผะตะฝะธ endDateOfSaleStageLast. */ SaleStageLast, /** * ะกะพัั‚ะพัะฝะธะต ะฝะฐัั‚ัƒะฟะฐัŽั‰ะตะต ะฟะพัะปะต ะทะฐะฒะตั€ัˆะตะฝะธั Ico, * ะฟั€ะธ ะฝะฐัั‚ัƒะฟะปะตะฝะธะธ ะดะฐะฝะฝะพะณะพ ัะพัั‚ะพัะฝะธั ัะฒะพะฑะพะดะฝั‹ะต ั‚ะพะบะตะฝั‹ ัะพั…ั€ะฐะฝััŽั‚ัั ะฒ unsoldTokens, * ั‚ะฐะบะถะต ะฟั€ะพะธัั…ะพะดะธั‚ ะฑะพะฝัƒัะฝะพะต ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะต ะดะพะฟะพะปะฝะธั‚ะตะปัŒะฝั‹ั… ั‚ะพะบะตะฝะพะฒ Bounty ะธ Team, * ะก ะผะพะผะตะฝั‚ะฐ ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco ะฟะพะบัƒะฟะบะฐ ั‚ะพะบะตะฝะพะฒ ะฝะตะฒะพะทะผะพะถะฝะฐ */ PostIco } /** * ะ—ะดะตััŒ ั…ั€ะฐะฝะธะผ ะฑะฐะปะฐะฝัั‹ ั‚ะพะบะตะฝะพะฒ */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * ะ—ะดะตััŒ ั…ั€ะฐะฝะธะผ ะฝะฐั‡ะธัะปะตะฝะฝั‹ะต ะฟั€ะตะผะธะฐะปัŒะฝั‹ะต ั‚ะพะบะตะฝั‹, ะผะพะณัƒั‚ ะฑั‹ั‚ัŒ ะฒั‹ะฒะตะดะตะฝั‹ ะฝะฐ ะบะพัˆะตะปั‘ะบ ะฝะฐั‡ะธะฝะฐั ั ะดะฐั‚ั‹ startDateOfUseTeamTokens */ mapping (address => uint256) teamBalances; /** * ะ’ะปะฐะดะตะปะตั† ะบะพะฝั‚ั€ะฐะบั‚ะฐ - ั€ะฐัะฟั€ะตะดะตะปัะตั‚ ะฒะธะฟ ั‚ะพะบะตะฝั‹, ะฝะฐั‡ะธัะปัะตั‚ ะฑะฐัƒะฝั‚ะธ ะธ team, ะพััƒั‰ะตัั‚ะฒะปัะตั‚ ะฟะตั€ะตั…ะพะด ะฟะพ ัั‚ะฐะดะธัะผ, */ address public owner; /** * ะฃั‡ะฐัั‚ะฝะธะบ ะบะพะฝั‚ั€ะฐะบั‚ะฐ - ะฒั‹ะฒะพะดะธั‚ eth ะฟะพัะปะต ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco, ัะพะฒะผะตัั‚ะฝะพ ั withdrawal2 */ address public withdrawal1; /** * ะฃั‡ะฐัั‚ะฝะธะบ ะบะพะฝั‚ั€ะฐะบั‚ะฐ - ั‚ะพะปัŒะบะพ ะฟั€ะธ ะตะณะพ ัƒั‡ะฐัั‚ะธะธ ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ะฒั‹ะฒะตะดะตะฝั‹ eth ะฟะพัะปะต ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco, ัะพะฒะผะตัั‚ะฝะพ ั withdrawal1 */ address public withdrawal2; /** * ะะดั€ะตั ะฝะฐ ัั‡ั‘ั‚ะต ะบะพั‚ะพั€ะพะณะพ ะฝะฐั…ะพะดัั‚ัั ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ะต bounty ั‚ะพะบะตะฝั‹ */ address public bountyTokensAccount; /** * ะะดั€ะตั ะฝะฐ ัั‡ั‘ั‚ะต ะบะพั‚ะพั€ะพะณะพ ะฝะฐั…ะพะดัั‚ัั ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ะต team ั‚ะพะบะตะฝั‹ */ address public teamTokensAccount; /** *ะะดั€ะตั ะฝะฐ ะบะพั‚ะพั€ั‹ะน ะธะฝะธั†ะธะธั€ะพะฒะฐะฝ ะฒั‹ะฒะพะด eth (ะฒะปะฐะดะตะปัŒั†ะตะผ) */ address public withdrawalTo; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ eth ะบะพั‚ะพั€ั‹ะน ะฟั€ะตะดะฟะพะปะฐะณะฐะตั‚ัั ะฒั‹ะฒะพะดะธั‚ัŒ ะฝะฐ ะฐะดั€ะตั withdrawalTo */ uint256 public withdrawalValue; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ bounty * */ uint256 public bountyTokensNotDistributed; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ team * */ uint256 public teamTokensNotDistributed; /** * ะขะตะบัƒั‰ะตะต ัะพัั‚ะพัะฝะธะต */ IcoStates public currentState; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ัะพะฑั€ะฐะฝะฝะพะณะพ ัั„ะธั€ะฐ */ uint256 public totalBalance; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ (ะฝะธะบั‚ะพ ะธะผะธ ะฝะต ะฒะปะฐะดะตะตั‚) */ uint256 public freeMoney = 0; /** * ะžะฑั‰ะตะต ะบะพะปะธั‡ะตัั‚ะฒะพ ะฒั‹ะฟัƒั‰ะตะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ * */ uint256 public totalSupply = 0; /** * ะžะฑั‰ะตะต ะบะพะปะธั‡ะตัั‚ะฒะพ ะบัƒะฟะปะตะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ * */ uint256 public totalBought = 0; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ะฝะต ั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะพั‚ ัั‚ะฐะดะธะธ VipPlacement */ uint256 public vipPlacementNotDistributed; /** * ะ”ะฐั‚ะฐ ะพะบะพะฝั‡ะฐะฝะธั ัั‚ะฐะดะธะธ VipPlacement */ uint256 public endDateOfVipPlacement; /** * ะ”ะฐั‚ะฐ ะพะบะพะฝั‡ะฐะฝะธั ัั‚ะฐะดะธะธ PreSale */ uint256 public endDateOfPreSale = 0; /** * ะ”ะฐั‚ะฐ ะฝะฐั‡ะฐะปะฐ ัั‚ะฐะดะธะธ SaleStageLast */ uint256 public startDateOfSaleStageLast; /** * ะ”ะฐั‚ะฐ ะพะบะพะฝั‡ะฐะฝะธั ัั‚ะฐะดะธะธ SaleStageLast */ uint256 public endDateOfSaleStageLast = 0; /** * ะžัั‚ะฐั‚ะพะบ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะดะปั ัะพัั‚ะพัะฝะธะน ั SaleStage1 ะฟะพ SaleStage7, ะบะพั‚ะพั€ั‹ะต ะฟะตั€ะตั…ะพะดัั‚ ะฒ ัะฒะพะฑะพะดะฝั‹ะต ะฝะฐ ะผะพะผะตะฝั‚ ะฝะฐัั‚ัƒะฟะปะตะฝะธั SaleStageLast */ uint256 public remForSalesBeforeStageLast = 0; /** * ะ”ะฐั‚ะฐ, ะฝะฐั‡ะธะฝะฐั ั ะบะพั‚ะพั€ะพะน ะผะพะถะฝะพ ะฟะพะปัƒั‡ะธั‚ัŒ team ั‚ะพะบะตะฝั‹ ะฝะตะฟะพัั€ะตะดัั‚ะฒะตะฝะฝะพ ะฝะฐ ะบะพัˆะตะปั‘ะบ */ uint256 public startDateOfUseTeamTokens = 0; /** * ะ”ะฐั‚ะฐ, ะฝะฐั‡ะธะฝะฐั ั ะบะพั‚ะพั€ะพะน ะผะพะถะฝะพ ะฒะพััั‚ะฐะฝะพะฒะธั‚ัŒ-ะฟะตั€ะตะฒะตัั‚ะธ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ะต ั‚ะพะบะตะฝั‹ unsoldTokens */ uint256 public startDateOfRestoreUnsoldTokens = 0; /** * ะšะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฝะฐ ะผะพะผะตะฝั‚ ะฝะฐัั‚ัƒะฟะปะตะฝะธั PostIco */ uint256 public unsoldTokens = 0; /** * How many token units a buyer gets per wei */ uint256 public rate = 0; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the withdrawal1. */ modifier onlyWithdrawal1() { require(msg.sender == withdrawal1); _; } /** * @dev Throws if called by any account other than the withdrawal2. */ modifier onlyWithdrawal2() { require(msg.sender == withdrawal2); _; } /** * ะœะพะดะธั„ะธะบะฐั‚ะพั€ ะฟะพะทะฒะพะปััŽั‰ะธะน ะฒั‹ะฟะพะปะฝัั‚ัŒ ะฒั‹ะทะพะฒ, * ั‚ะพะปัŒะบะพ ะตัะปะธ ัะพัั‚ะพัะฝะธะต PostIco ะธะปะธ ะฒั‹ัˆะต */ modifier afterIco() { require(uint(currentState) >= uint(IcoStates.PostIco)); _; } /** * ะœะพะดะธั„ะธะบะฐั‚ะพั€ ะฟั€ะพะฒะตั€ััŽั‰ะธะน ะดะพะฟัƒัั‚ะธะผะพัั‚ัŒ ะพะฟะตั€ะฐั†ะธะน transfer */ modifier checkForTransfer(address _from, address _to, uint256 _value) { //ะฟั€ะพะฒะตั€ัะตะผ ั€ะฐะทะผะตั€ ะฟะตั€ะตะฒะพะดะฐ require(_value > 0); //ะฟั€ะพะฒะตั€ัะตะผ ะบะพัˆะตะปั‘ะบ ะฝะฐะทะฝะฐั‡ะตะฝะธั require(_to != 0x0 && _to != _from); //ะฝะฐ ัั‚ะฐะดะธัั… ะฟะตั€ะตะด ico ะฟะตั€ะตะฒะพะดะธั‚ัŒ ะผะพะถะตั‚ ั‚ะพะปัŒะบะพ ะฒะปะฐะดะตะปะตั† require(currentState == IcoStates.PostIco || _from == owner); //ะพะฟะตั€ะฐั†ะธะธ ะฝะฐ bounty ะธ team ะฝะต ะดะพะฟัƒัั‚ะธะผั‹ ะดะพ ะพะบะพะฝั‡ะฐะฝะธั ico require(currentState == IcoStates.PostIco || (_to != bountyTokensAccount && _to != teamTokensAccount)); _; } /** * ะกะพะฑั‹ั‚ะธะต ะธะทะผะตะฝะตะฝะธั ัะพัั‚ะพัะฝะธั ะบะพะฝั‚ั€ะฐะบั‚ะฐ */ event StateChanged(IcoStates state); /** * ะกะพะฑั‹ั‚ะธะต ะฟะพะบัƒะฟะบะธ ั‚ะพะบะตะฝะพะฒ */ event Buy(address beneficiary, uint256 boughtTokens, uint256 ethValue); /** * @dev ะšะพะฝัั‚ั€ัƒะบั‚ะพั€ */ function RobomedIco() public { //ะฟั€ะพะฒะตั€ัะตะผ, ั‡ั‚ะพ ะฒัะต ัƒะบะฐะทะฐะฝะฝั‹ะต ะฐะดั€ะตัะฐ ะฝะต ั€ะฐะฒะฝั‹ 0, ั‚ะฐะบะถะต ะพะฝะธ ะพั‚ะปะธั‡ะฐัŽั‚ัั ะพั‚ ัะพะทะดะฐัŽั‰ะตะณะพ ะบะพะฝั‚ั€ะฐะบั‚ //ะฟะพ ััƒั‚ะธ ะบะพะฝั‚ั€ะฐะบั‚ ัะพะทะดะฐั‘ั‚ ะฝะตะบะพะต 3-ะตะต ะปะธั†ะพ ะฝะต ะธะผะตัŽั‰ะตะต ะฒ ะดะฐะปัŒะฝะตะนัˆะตะผ ะฝะธ ะบะฐะบะธั… ะพัะพะฑะตะฝะฝั‹ั… ะฟั€ะฐะฒ //ั‚ะฐะบ ะถะต ะดะตะนัั‚ะฒัƒะตั‚ ัƒัะปะพะฒะธะต ั‡ั‚ะพ ะฒัะต ะฟะตั€ะธั‡ะธัะปะตะฝะฝั‹ะต ะฐะดั€ะตัะฐ ั€ะฐะทะฝั‹ะต (ะฝะตะปัŒะทั ะฑั‹ั‚ัŒ ะพะดะฝะพะฒั€ะตะผะตะฝะฝะพ ะฒะปะฐะดะตะปัŒั†ะตะผ ะธ ะบะพัˆะตะปัŒะบะพะผ ะดะปั ั‚ะพะบะตะฝะพะฒ - ะฝะฐะฟั€ะธะผะตั€) require(ADDR_OWNER != 0x0 && ADDR_OWNER != msg.sender); require(ADDR_WITHDRAWAL1 != 0x0 && ADDR_WITHDRAWAL1 != msg.sender); require(ADDR_WITHDRAWAL2 != 0x0 && ADDR_WITHDRAWAL2 != msg.sender); require(ADDR_BOUNTY_TOKENS_ACCOUNT != 0x0 && ADDR_BOUNTY_TOKENS_ACCOUNT != msg.sender); require(ADDR_TEAM_TOKENS_ACCOUNT != 0x0 && ADDR_TEAM_TOKENS_ACCOUNT != msg.sender); require(ADDR_BOUNTY_TOKENS_ACCOUNT != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_OWNER != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_OWNER != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL1 != ADDR_OWNER); require(ADDR_WITHDRAWAL1 != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL1 != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_OWNER); require(ADDR_WITHDRAWAL2 != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_WITHDRAWAL1); //ะฒั‹ัั‚ะฐะฒะปัะตะผ ะฐะดั€ะตัะฐ //test owner = ADDR_OWNER; withdrawal1 = ADDR_WITHDRAWAL1; withdrawal2 = ADDR_WITHDRAWAL2; bountyTokensAccount = ADDR_BOUNTY_TOKENS_ACCOUNT; teamTokensAccount = ADDR_TEAM_TOKENS_ACCOUNT; //ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะฝะฐั‡ะฐะปัŒะฝะพะต ะทะฝะฐั‡ะตะฝะธะต ะฝะฐ ะฟั€ะตะดะพะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… ะฐะบะบะฐัƒะฝั‚ะฐั… balances[owner] = INITIAL_COINS_FOR_VIPPLACEMENT; balances[bountyTokensAccount] = EMISSION_FOR_BOUNTY; balances[teamTokensAccount] = EMISSION_FOR_TEAM; //ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ะต ั‚ะพะบะตะฝั‹ bountyTokensNotDistributed = EMISSION_FOR_BOUNTY; teamTokensNotDistributed = EMISSION_FOR_TEAM; vipPlacementNotDistributed = INITIAL_COINS_FOR_VIPPLACEMENT; currentState = IcoStates.VipPlacement; totalSupply = INITIAL_COINS_FOR_VIPPLACEMENT + EMISSION_FOR_BOUNTY + EMISSION_FOR_TEAM; endDateOfVipPlacement = now.add(DURATION_VIPPLACEMENT); remForSalesBeforeStageLast = 0; //set team for members owner = msg.sender; //ildar transferTeam(0xa19DC4c158169bC45b17594d3F15e4dCb36CC3A3, TEAM_MEMBER_VAL); //vova transferTeam(0xdf66490Fe9F2ada51967F71d6B5e26A9D77065ED, TEAM_MEMBER_VAL); //kirill transferTeam(0xf0215C6A553AD8E155Da69B2657BeaBC51d187c5, TEAM_MEMBER_VAL); //evg transferTeam(0x6c1666d388302385AE5c62993824967a097F14bC, TEAM_MEMBER_VAL); //igor transferTeam(0x82D550dC74f8B70B202aB5b63DAbe75E6F00fb36, TEAM_MEMBER_VAL); owner = ADDR_OWNER; } /** * Function to access name of token . */ function name() public constant returns (string) { return name; } /** * Function to access symbol of token . */ function symbol() public constant returns (string) { return symbol; } /** * Function to access decimals of token . */ function decimals() public constant returns (uint8) { return decimals; } /** * Function to access total supply of tokens . */ function totalSupply() public constant returns (uint256) { return totalSupply; } /** * ะœะตั‚ะพะด ะฟะพะปัƒั‡ะฐัŽั‰ะธะน ะบะพะปะธั‡ะตัั‚ะฒะพ ะฝะฐั‡ะธัะปะตะฝะฝั‹ั… ะฟั€ะตะผะธะฐะปัŒะฝั‹ั… ั‚ะพะบะตะฝะพะฒ */ function teamBalanceOf(address _owner) public constant returns (uint256){ return teamBalances[_owner]; } /** * ะœะตั‚ะพะด ะทะฐั‡ะธัะปััŽั‰ะธะน ะฟั€ะตะดะฒะฐั€ะธั‚ะตะปัŒะฝะพ ั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ะต team ั‚ะพะบะตะฝั‹ ะฝะฐ ะบะพัˆะตะปั‘ะบ */ function accrueTeamTokens() public afterIco { //ะทะฐั‡ะธัะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ะฟะพัะปะต ะพะฟั€ะตะดะตะปั‘ะฝะฝะพะน ะดะฐั‚ั‹ require(startDateOfUseTeamTokens <= now); //ะดะพะฑะฐะฒะปัะตะผ ะฒ ะพะฑั‰ะตะต ะบะพะปะธั‡ะตัั‚ะฒะพ ะฒั‹ะฟัƒั‰ะตะฝะฝั‹ั… totalSupply = totalSupply.add(teamBalances[msg.sender]); //ะทะฐั‡ะธัะปัะตะผ ะฝะฐ ะบะพัˆะตะปั‘ะบ ะธ ะพะฑะฝัƒะปัะตะผ ะฝะต ะฝะฐั‡ะธัะปะตะฝะฝั‹ะต balances[msg.sender] = balances[msg.sender].add(teamBalances[msg.sender]); teamBalances[msg.sender] = 0; } /** * ะœะตั‚ะพะด ะฟั€ะพะฒะตั€ััŽั‰ะธะน ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฒะพััั‚ะฐะฝะพะฒะปะตะฝะธั ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ */ function canRestoreUnsoldTokens() public constant returns (bool) { //ะฒะพััั‚ะฐะฝะพะฒะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ะฟะพัะปะต ico if (currentState != IcoStates.PostIco) return false; //ะฒะพััั‚ะฐะฝะพะฒะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ะฟะพัะปะต ะพะฟั€ะตะดะตะปั‘ะฝะฝะพะน ะดะฐั‚ั‹ if (startDateOfRestoreUnsoldTokens > now) return false; //ะฒะพััั‚ะฐะฝะพะฒะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ะตัะปะธ ะตัั‚ัŒ ั‡ั‚ะพ ะฒะพััั‚ะฐะฝะฐะฒะปะธะฒะฐั‚ัŒ if (unsoldTokens == 0) return false; return true; } /** * ะœะตั‚ะพะด ะฒั‹ะฟะพะปะฝััŽั‰ะธะน ะฒะพััั‚ะฐะฝะพะฒะปะตะฝะธะต ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ */ function restoreUnsoldTokens(address _to) public onlyOwner { require(_to != 0x0); require(canRestoreUnsoldTokens()); balances[_to] = balances[_to].add(unsoldTokens); totalSupply = totalSupply.add(unsoldTokens); unsoldTokens = 0; } /** * ะœะตั‚ะพะด ะฟะตั€ะตะฒะพะดัั‰ะธะน ะบะพะฝั‚ั€ะฐะบั‚ ะฒ ัะปะตะดัƒัŽั‰ะตะต ะดะพัั‚ัƒะฟะฝะพะต ัะพัั‚ะพัะฝะธะต, * ะ”ะปั ะฒั‹ััะฝะตะฝะธั ะฒะพะทะผะพะถะฝะพัั‚ะธ ะฟะตั€ะตั…ะพะดะฐ ะผะพะถะฝะพ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ะผะตั‚ะพะด canGotoState */ function gotoNextState() public onlyOwner returns (bool) { if (gotoPreSale() || gotoSaleStage1() || gotoSaleStageLast() || gotoPostIco()) { return true; } return false; } /** * ะ˜ะฝะธั†ะธะฐั†ะธั ัะฝัั‚ะธั ัั„ะธั€ะฐ ะฝะฐ ัƒะบะฐะทะฐะฝะฝั‹ะน ะบะพัˆะตะปั‘ะบ */ function initWithdrawal(address _to, uint256 _value) public afterIco onlyWithdrawal1 { withdrawalTo = _to; withdrawalValue = _value; } /** * ะŸะพะดั‚ะฒะตั€ะถะดะตะฝะธะต ัะฝัั‚ะธั ัั„ะธั€ะฐ ะฝะฐ ัƒะบะฐะทะฐะฝะฝั‹ะน ะบะพัˆะตะปั‘ะบ */ function approveWithdrawal(address _to, uint256 _value) public afterIco onlyWithdrawal2 { require(_to != 0x0 && _value > 0); require(_to == withdrawalTo); require(_value == withdrawalValue); totalBalance = totalBalance.sub(_value); withdrawalTo.transfer(_value); withdrawalTo = 0x0; withdrawalValue = 0; } /** * ะœะตั‚ะพะด ะฟั€ะพะฒะตั€ััŽั‰ะธะน ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฟะตั€ะตั…ะพะดะฐ ะฒ ัƒะบะฐะทะฐะฝะฝะพะต ัะพัั‚ะพัะฝะธะต */ function canGotoState(IcoStates toState) public constant returns (bool){ if (toState == IcoStates.PreSale) { return (currentState == IcoStates.VipPlacement && endDateOfVipPlacement <= now); } else if (toState == IcoStates.SaleStage1) { return (currentState == IcoStates.PreSale && endDateOfPreSale <= now); } else if (toState == IcoStates.SaleStage2) { return (currentState == IcoStates.SaleStage1 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage3) { return (currentState == IcoStates.SaleStage2 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage4) { return (currentState == IcoStates.SaleStage3 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage5) { return (currentState == IcoStates.SaleStage4 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage6) { return (currentState == IcoStates.SaleStage5 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage7) { return (currentState == IcoStates.SaleStage6 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStageLast) { //ะฟะตั€ะตั…ะพะด ะฝะฐ ัะพัั‚ะพัะฝะธะต SaleStageLast ะฒะพะทะผะพะถะตะฝ ั‚ะพะปัŒะบะพ ะธะท ัะพัั‚ะพัะฝะธะน SaleStages if ( currentState != IcoStates.SaleStage1 && currentState != IcoStates.SaleStage2 && currentState != IcoStates.SaleStage3 && currentState != IcoStates.SaleStage4 && currentState != IcoStates.SaleStage5 && currentState != IcoStates.SaleStage6 && currentState != IcoStates.SaleStage7) return false; //ะฟะตั€ะตั…ะพะด ะพััƒั‰ะตัั‚ะฒะปัะตั‚ัั ะตัะปะธ ะฝะฐ ัะพัั‚ะพัะฝะธะธ SaleStage7 ะฝะต ะพัั‚ะฐะปะพััŒ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ //ะธะปะธ ะฝะฐ ะพะดะฝะพะผ ะธะท ัะพัั‚ะพัะฝะธะน SaleStages ะฝะฐัั‚ัƒะฟะธะปะพ ะฒั€ะตะผั startDateOfSaleStageLast if (!(currentState == IcoStates.SaleStage7 && freeMoney == 0) && startDateOfSaleStageLast > now) { return false; } return true; } else if (toState == IcoStates.PostIco) { return (currentState == IcoStates.SaleStageLast && endDateOfSaleStageLast <= now); } } /** * Fallback ั„ัƒะฝะบั†ะธั - ะธะท ะฝะตั‘ ะฟะพ ััƒั‚ะธ ะฟั€ะพัั‚ะพ ะฟั€ะพะธัั…ะพะดะธั‚ ะฒั‹ะทะพะฒ ะฟะพะบัƒะฟะบะธ ั‚ะพะบะตะฝะพะฒ ะดะปั ะพั‚ะฟั€ะฐะฒะธั‚ะตะปั */ function() public payable { buyTokens(msg.sender); } /** * ะœะตั‚ะพะด ะฟะพะบัƒะฟะบะธ ั‚ะพะบะตะฝะพะฒ */ function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(msg.value != 0); //ะฝะตะปัŒะทั ะฟะพะบัƒะฟะฐั‚ัŒ ะฝะฐ ั‚ะพะบะตะฝั‹ bounty ะธ team require(beneficiary != bountyTokensAccount && beneficiary != teamTokensAccount); //ะฒั‹ัั‚ะฐะฒะปัะตะผ ะพัั‚ะฐั‚ะพะบ ัั€ะตะดัั‚ะฒ //ะฒ ะฟั€ะพั†ะตััะต ะฟะพะบัƒะฟะบะธ ะฑัƒะดะตะผ ะตะณะพ ัƒะผะตะฝัŒัˆะฐั‚ัŒ ะฝะฐ ะบะฐะถะดะพะน ะธั‚ะตั€ะฐั†ะธะธ - ะธั‚ะตั€ะฐั†ะธั - ะฟะพะบัƒะฟะบะฐ ั‚ะพะบะตะฝะพะฒ ะฝะฐ ะพะฟั€ะตะดะตะปั‘ะฝะฝะพะน ัั‚ะฐะดะธะธ //ััƒั‚ัŒ - ะตัะปะธ ะฟะพะบัƒะฟะฐัŽั‰ะธะน ะฟะตั€ะตะฒะพะดะธั‚ ะบะพะปะธั‡ะตัั‚ะฒะพ ัั„ะธั€ะฐ, //ะฑะพะปัŒัˆะตะต ั‡ะตะผ ะฒะพะทะผะพะถะฝะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฝะฐ ะพะฟั€ะตะดะตะปั‘ะฝะฝะพะน ัั‚ะฐะดะธะธ, //ั‚ะพ ะฒั‹ะฟะพะปะฝัะตั‚ัั ะฟะตั€ะตั…ะพะด ะฝะฐ ัะปะตะดัƒัŽั‰ัƒัŽ ัั‚ะฐะดะธัŽ (ะบัƒั€ั ั‚ะพะถะต ะผะตะฝัะตั‚ัั) //ะธ ะฝะฐ ะพัั‚ะฐั‚ะพะบ ะธะดั‘ั‚ ะฟะพะบัƒะฟะบะฐ ะฝะฐ ะฝะพะฒะพะน ัั‚ะฐะดะธะธ ะธ ั‚.ะด. //ะตัะปะธ ะถะต ะฒ ะฟั€ะพั†ะตััะต ะฟะพะบัƒะฟะบะต ะฒัะต ัะฒะพะฑะพะดะฝั‹ะต ั‚ะพะบะตะฝั‹ ะธะทั€ะฐัั…ะพะดัƒัŽั‚ัั (ัะพ ะฒัะตั… ะดะพะฟัƒัั‚ะธะผั‹ั… ัั‚ะฐะดะธะน) //ะฑัƒะดะตั‚ ะฒั‹ะบะธะฝัƒั‚ะพ ะธัะบะปัŽั‡ะตะฝะธะต uint256 remVal = msg.value; //ัƒะฒะตะปะธั‡ะธะฒะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ัั„ะธั€ะฐ ะฟั€ะธัˆะตะดัˆะตะณะพ ะบ ะฝะฐะผ totalBalance = totalBalance.add(msg.value); //ะพะฑั‰ะตะต ะบะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ ะบะพั‚ะพั€ั‹ะต ะบัƒะฟะธะปะธ ะทะฐ ัั‚ะพั‚ ะฒั‹ะทะพะฒ uint256 boughtTokens = 0; while (remVal > 0) { //ะฟะพะบัƒะฟะฐั‚ัŒ ั‚ะพะบะตะฝั‹ ะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ะฝะฐ ัƒะบะฐะทะฐะฝะฝั‹ั… ัั‚ะฐะดะธัั… require( currentState != IcoStates.VipPlacement && currentState != IcoStates.PostIco); //ะฒั‹ะฟะพะปะฝัะตะผ ะฟะพะบัƒะฟะบัƒ ะดะปั ะฒั‹ะทั‹ะฒะฐัŽั‰ะตะณะพ //ัะผะพั‚ั€ะธะผ, ะตัั‚ัŒ ะปะธ ัƒ ะฝะฐั ั‚ะฐะบะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะฝะฐ ั‚ะตะบัƒั‰ะตะน ัั‚ะฐะดะธะธ uint256 tokens = remVal.mul(rate); if (tokens > freeMoney) { remVal = remVal.sub(freeMoney.div(rate)); tokens = freeMoney; } else { remVal = 0; //ะตัะปะธ ะพัั‚ะฐั‚ะพะบ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ ะผะตะฝัŒัˆะต ั‡ะตะผ ะบัƒั€ั - ะพั‚ะดะฐั‘ะผ ะธั… ะฟะพะบัƒะฟะฐั‚ะตะปัŽ uint256 remFreeTokens = freeMoney.sub(tokens); if (0 < remFreeTokens && remFreeTokens < rate) { tokens = freeMoney; } } assert(tokens > 0); freeMoney = freeMoney.sub(tokens); totalBought = totalBought.add(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); boughtTokens = boughtTokens.add(tokens); //ะตัะปะธ ะฟะพะบัƒะฟะบะฐ ะฑั‹ะปะฐ ะฒั‹ะฟะพะปะฝะตะฝะฐ ะฝะฐ ะปัŽะฑะพะน ะธะท ัั‚ะฐะดะธะน Sale ะบั€ะพะผะต ะฟะพัะปะตะดะฝะตะน if ( uint(currentState) >= uint(IcoStates.SaleStage1) && uint(currentState) <= uint(IcoStates.SaleStage7)) { //ัƒะผะตะฝัŒัˆะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะพัั‚ะฐั‚ะบะฐ ะฟะพ ั‚ะพะบะตะฝะฐะผ ะบะพั‚ะพั€ั‹ะต ะฝะตะพะฑั…ะพะดะธะผะพ ะฟั€ะพะดะฐั‚ัŒ ะฝะฐ ัั‚ะธั… ัั‚ะฐะดะธัั… remForSalesBeforeStageLast = remForSalesBeforeStageLast.sub(tokens); //ะฟั€ะพะฑัƒะตะผ ะฟะตั€ะตะนั‚ะธ ะผะตะถะดัƒ SaleStages transitionBetweenSaleStages(); } } Buy(beneficiary, boughtTokens, msg.value); } /** * ะœะตั‚ะพะด ะฒั‹ะฟะพะปะฝััŽั‰ะธะน ะฒั‹ะดะฐั‡ัƒ ะฑะฐัƒะฝั‚ะธ-ั‚ะพะบะตะฝะพะฒ ะฝะฐ ัƒะบะฐะทะฐะฝะฝั‹ะน ะฐะดั€ะตั */ function transferBounty(address _to, uint256 _value) public onlyOwner { //ะฟั€ะพะฒะตั€ัะตะผ ะบะพัˆะตะปั‘ะบ ะฝะฐะทะฝะฐั‡ะตะฝะธั require(_to != 0x0 && _to != msg.sender); //ัƒะผะตะฝัŒัˆะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… bountyTokensNotDistributed = bountyTokensNotDistributed.sub(_value); //ะฟะตั€ะตะฒะพะดะธะผ ั ะฐะบะฐัƒะฝั‚ะฐ ะฑะฐัƒะฝั‚ะธ ะฝะฐ ะฐะบะฐัƒะฝั‚ ะฝะฐะทะฝะฐั‡ะตะฝะธั balances[_to] = balances[_to].add(_value); balances[bountyTokensAccount] = balances[bountyTokensAccount].sub(_value); Transfer(bountyTokensAccount, _to, _value); } /** * ะœะตั‚ะพะด ะฒั‹ะฟะพะปะฝััŽั‰ะธะน ะฒั‹ะดะฐั‡ัƒ ะฑะฐัƒะฝั‚ะธ-ั‚ะพะบะตะฝะพะฒ ะฝะฐ ัƒะบะฐะทะฐะฝะฝั‹ะน ะฐะดั€ะตั */ function transferTeam(address _to, uint256 _value) public onlyOwner { //ะฟั€ะพะฒะตั€ัะตะผ ะบะพัˆะตะปั‘ะบ ะฝะฐะทะฝะฐั‡ะตะฝะธั require(_to != 0x0 && _to != msg.sender); //ัƒะผะตะฝัŒัˆะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะตะดะตะปั‘ะฝะฝั‹ั… teamTokensNotDistributed = teamTokensNotDistributed.sub(_value); //ะฟะตั€ะตะฒะพะดะธะผ ั ะฐะบะฐัƒะฝั‚ะฐ team ะฝะฐ team ะฐะบะฐัƒะฝั‚ ะฝะฐะทะฝะฐั‡ะตะฝะธั teamBalances[_to] = teamBalances[_to].add(_value); balances[teamTokensAccount] = balances[teamTokensAccount].sub(_value); //ัƒะฑะธั€ะฐะตะผ ั‚ะพะบะตะฝั‹ ะธะท ะพะฑั‰ะตะณะพ ะบะพะปะธั‡ะตัั‚ะฒะฐ ะฒั‹ะฟัƒั‰ะตะฝะฝั‹ั… totalSupply = totalSupply.sub(_value); } /** * Function that is called when a user or another contract wants to transfer funds . */ function transfer(address _to, uint _value, bytes _data) checkForTransfer(msg.sender, _to, _value) public returns (bool) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev transfer token for a specified address * Standard function transfer similar to ERC20 transfer with no _data . * Added due to backwards compatibility reasons . * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) checkForTransfer(msg.sender, _to, _value) public returns (bool) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } /** * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } /** * function that is called when transaction target is an address */ function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { _transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /** * function that is called when transaction target is a contract */ function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { _transfer(msg.sender, _to, _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function _transfer(address _from, address _to, uint _value) private { require(balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (currentState != IcoStates.PostIco) { //ะพะฑั‰ะฐั ััƒะผะผะฐ ะฟะตั€ะตะฒะพะดะพะฒ ะพั‚ ะฒะปะฐะดะตะปัŒั†ะฐ (ะดะพ ะทะฐะฒะตั€ัˆะตะฝะธั) ico ะฝะต ะผะพะถะตั‚ ะฟั€ะตะฒั‹ัˆะฐั‚ัŒ InitialCoinsFor_VipPlacement vipPlacementNotDistributed = vipPlacementNotDistributed.sub(_value); } } /** * @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]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public afterIco returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public afterIco returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * ะ’ัะฟะพะผะพะณะฐั‚ะตะปัŒะฝั‹ะน ะผะตั‚ะพะด ะฒั‹ัั‚ะฐะฒะปััŽั‰ะธะน ะบะพะปะธั‡ะตัั‚ะฒะพ ัะฒะพะฑะพะดะฝั‹ั… ั‚ะพะบะตะฝะพะฒ, ั€ะตะนั‚ ะธ ะดะพะฑะฐะฒะปััŽั‰ะธะน ะบะพะปะธั‡ะตัั‚ะฒะพ ัะผะธั‚ะธั€ะพะฒะฐะฝะฝั‹ั… */ function setMoney(uint256 _freeMoney, uint256 _emission, uint256 _rate) private { freeMoney = _freeMoney; totalSupply = totalSupply.add(_emission); rate = _rate; } /** * ะœะตั‚ะพะด ะฟะตั€ะตะฒะพะดัั‰ะธะน ะบะพะฝั‚ั€ะฐะบั‚ ะฒ ัะพัั‚ะพัะฝะธะต PreSale */ function gotoPreSale() private returns (bool) { //ะฟั€ะพะฒะตั€ัะตะผ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฟะตั€ะตั…ะพะดะฐ if (!canGotoState(IcoStates.PreSale)) return false; //ะดะฐ ะฝัƒะถะฝะพ ะฟะตั€ะตั…ะพะดะธั‚ัŒ //ะฟะตั€ะตั…ะพะดะธะผ ะฒ PreSale currentState = IcoStates.PreSale; //ะฒั‹ัั‚ะฐะฒะปัะตะผ ัะพัั‚ะพัะฝะธะต ั‚ะพะบะตะฝะพะฒ setMoney(EMISSION_FOR_PRESALE, EMISSION_FOR_PRESALE, RATE_PRESALE); //ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะดะฐั‚ัƒ ะพะบะพะฝั‡ะฐะฝะธั PreSale endDateOfPreSale = now.add(DURATION_PRESALE); //ั€ะฐะทะธะผ ัะพะฑั‹ั‚ะธะต ะธะทะผะตะฝะตะฝะธั ัะพัั‚ะพัะฝะธั StateChanged(IcoStates.PreSale); return true; } /** * ะœะตั‚ะพะด ะฟะตั€ะตะฒะพะดัั‰ะธะน ะบะพะฝั‚ั€ะฐะบั‚ ะฒ ัะพัั‚ะพัะฝะธะต SaleStage1 */ function gotoSaleStage1() private returns (bool) { //ะฟั€ะพะฒะตั€ัะตะผ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฟะตั€ะตั…ะพะดะฐ if (!canGotoState(IcoStates.SaleStage1)) return false; //ะดะฐ ะฝัƒะถะฝะพ ะฟะตั€ะตั…ะพะดะธั‚ัŒ //ะฟะตั€ะตั…ะพะดะธะผ ะฒ SaleStage1 currentState = IcoStates.SaleStage1; //ะฝะตะฟั€ะพะดะฐะฝะฝั‹ะต ั‚ะพะบะตะฝั‹ ัะณะพั€ะฐัŽั‚ totalSupply = totalSupply.sub(freeMoney); //ะฒั‹ัั‚ะฐะฒะปัะตะผ ัะพัั‚ะพัะฝะธะต ั‚ะพะบะตะฝะพะฒ setMoney(EMISSION_FOR_SALESTAGE1, EMISSION_FOR_SALESTAGE1, RATE_SALESTAGE1); //ะพะฟั€ะตะดะตะปัะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ั‚ะพะบะตะฝะพะฒ ะบะพั‚ะพั€ะพะต ะผะพะถะฝะพ ะฟั€ะพะดะฐั‚ัŒ ะฝะฐ ะฒัะตั… ัั‚ะฐะดะธัั… Sale ะบั€ะพะผะต ะฟะพัะปะตะดะฝะตะน remForSalesBeforeStageLast = EMISSION_FOR_SALESTAGE1 + EMISSION_FOR_SALESTAGE2 + EMISSION_FOR_SALESTAGE3 + EMISSION_FOR_SALESTAGE4 + EMISSION_FOR_SALESTAGE5 + EMISSION_FOR_SALESTAGE6 + EMISSION_FOR_SALESTAGE7; //ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะดะฐั‚ัƒ ะฝะฐั‡ะฐะปะฐ ะฟะพัะปะตะดะฝะตะน ัั‚ะฐะดะธะธ ะฟั€ะพะดะฐะถ startDateOfSaleStageLast = now.add(DURATION_SALESTAGES); //ั€ะฐะทะธะผ ัะพะฑั‹ั‚ะธะต ะธะทะผะตะฝะตะฝะธั ัะพัั‚ะพัะฝะธั StateChanged(IcoStates.SaleStage1); return true; } /** * ะœะตั‚ะพะด ะฒั‹ะฟะพะปะฝััŽั‰ะธะน ะฟะตั€ะตั…ะพะด ะผะตะถะดัƒ ัะพัั‚ะพัะฝะธัะผะธ Sale */ function transitionBetweenSaleStages() private { //ะฟะตั€ะตั…ะพะด ะผะตะถะดัƒ ัะพัั‚ะพัะฝะธัะผะธ SaleStages ะฒะพะทะผะพะถะตะฝ ั‚ะพะปัŒะบะพ ะตัะปะธ ะฝะฐั…ะพะดะธะผัั ะฒ ะพะดะฝะพะผ ะธะท ะฝะธั…, ะบั€ะพะผะต ะฟะพัะปะตะดะฝะตะณะพ if ( currentState != IcoStates.SaleStage1 && currentState != IcoStates.SaleStage2 && currentState != IcoStates.SaleStage3 && currentState != IcoStates.SaleStage4 && currentState != IcoStates.SaleStage5 && currentState != IcoStates.SaleStage6 && currentState != IcoStates.SaleStage7) return; //ะตัะปะธ ะตัั‚ัŒ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ัั€ะฐะทัƒ ะฟะตั€ะตั…ะพะดะธะผ ะฒ ัะพัั‚ะพัะฝะธะต StageLast if (gotoSaleStageLast()) { return; } //ัะผะพั‚ั€ะธะผ ะฒ ะบะฐะบะพะต ัะพัั‚ะพัะฝะธะต ะผะพะถะตะผ ะฟะตั€ะตะนั‚ะธ ะธ ะฒั‹ะฟะพะปะฝัะตะผ ะฟะตั€ะตั…ะพะด if (canGotoState(IcoStates.SaleStage2)) { currentState = IcoStates.SaleStage2; setMoney(EMISSION_FOR_SALESTAGE2, EMISSION_FOR_SALESTAGE2, RATE_SALESTAGE2); StateChanged(IcoStates.SaleStage2); } else if (canGotoState(IcoStates.SaleStage3)) { currentState = IcoStates.SaleStage3; setMoney(EMISSION_FOR_SALESTAGE3, EMISSION_FOR_SALESTAGE3, RATE_SALESTAGE3); StateChanged(IcoStates.SaleStage3); } else if (canGotoState(IcoStates.SaleStage4)) { currentState = IcoStates.SaleStage4; setMoney(EMISSION_FOR_SALESTAGE4, EMISSION_FOR_SALESTAGE4, RATE_SALESTAGE4); StateChanged(IcoStates.SaleStage4); } else if (canGotoState(IcoStates.SaleStage5)) { currentState = IcoStates.SaleStage5; setMoney(EMISSION_FOR_SALESTAGE5, EMISSION_FOR_SALESTAGE5, RATE_SALESTAGE5); StateChanged(IcoStates.SaleStage5); } else if (canGotoState(IcoStates.SaleStage6)) { currentState = IcoStates.SaleStage6; setMoney(EMISSION_FOR_SALESTAGE6, EMISSION_FOR_SALESTAGE6, RATE_SALESTAGE6); StateChanged(IcoStates.SaleStage6); } else if (canGotoState(IcoStates.SaleStage7)) { currentState = IcoStates.SaleStage7; setMoney(EMISSION_FOR_SALESTAGE7, EMISSION_FOR_SALESTAGE7, RATE_SALESTAGE7); StateChanged(IcoStates.SaleStage7); } } /** * ะœะตั‚ะพะด ะฟะตั€ะตะฒะพะดัั‰ะธะน ะบะพะฝั‚ั€ะฐะบั‚ ะฒ ัะพัั‚ะพัะฝะธะต SaleStageLast */ function gotoSaleStageLast() private returns (bool) { if (!canGotoState(IcoStates.SaleStageLast)) return false; //ะพะบ ะฟะตั€ะตั…ะพะดะธะผ ะฝะฐ ัะพัั‚ะพัะฝะธะต SaleStageLast currentState = IcoStates.SaleStageLast; //ะฒั‹ัั‚ะฐะฒะปัะตะผ ัะพัั‚ะพัะฝะธะต ั‚ะพะบะตะฝะพะฒ, ั ัƒั‡ั‘ั‚ะพะผ ะฒัะตั… ะพัั‚ะฐั‚ะบะพะฒ setMoney(remForSalesBeforeStageLast + EMISSION_FOR_SALESTAGELAST, EMISSION_FOR_SALESTAGELAST, RATE_SALESTAGELAST); //ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะดะฐั‚ัƒ ะพะบะพะฝั‡ะฐะฝะธั SaleStageLast endDateOfSaleStageLast = now.add(DURATION_SALESTAGELAST); StateChanged(IcoStates.SaleStageLast); return true; } /** * ะœะตั‚ะพะด ะฟะตั€ะตะฒะพะดัั‰ะธะน ะบะพะฝั‚ั€ะฐะบั‚ ะฒ ัะพัั‚ะพัะฝะธะต PostIco */ function gotoPostIco() private returns (bool) { if (!canGotoState(IcoStates.PostIco)) return false; //ะพะบ ะฟะตั€ะตั…ะพะดะธะผ ะฝะฐ ัะพัั‚ะพัะฝะธะต PostIco currentState = IcoStates.PostIco; //ะฒั‹ัั‚ะฐะฒะปัะตะผ ะดะฐั‚ัƒ ะฟะพัะปะต ะบะพั‚ะพั€ะพะน ะผะพะถะฝะพ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ะฟั€ะตะผะธะฐะปัŒะฝั‹ะต ั‚ะพะบะตะฝั‹ startDateOfUseTeamTokens = now + DURATION_NONUSETEAM; //ะฒั‹ัั‚ะฐะฒะปัะตะผ ะดะฐั‚ัƒ ะฟะพัะปะต ะบะพั‚ะพั€ะพะน ะผะพะถะฝะพ ะทะฐั‡ะธัะปัั‚ัŒ ะพัั‚ะฐะฒัˆะธะตัั (ะฝะต ั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ะต) ั‚ะพะบะตะฝั‹, ะฝะฐ ะฟั€ะพะธะทะฒะพะปัŒะฝั‹ะน ะบะพัˆะตะปั‘ะบ startDateOfRestoreUnsoldTokens = now + DURATION_BEFORE_RESTORE_UNSOLD; //ะทะฐะฟะพะผะธะฝะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฝะตั€ะฐัะฟั€ะพะดะฐะฝะฝั‹ั… ั‚ะพะบะตะฝะพะฒ unsoldTokens = freeMoney; //ัƒะฝะธั‡ั‚ะพะถะฐะตะผ ัะฒะพะฑะพะดะฝั‹ะต ั‚ะพะบะตะฝั‹ totalSupply = totalSupply.sub(freeMoney); setMoney(0, 0, 0); StateChanged(IcoStates.PostIco); return true; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amout of tokens to be transfered/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
function transferFrom(address _from, address _to, uint256 _value) public afterIco returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
5,365,246
./full_match/1/0x9e52dB44d62A8c9762FA847Bd2eBa9d0585782d1/sources/contracts/v2/core/SgETH.sol
Remove a minter - only callable by DEFAULT_ADMIN_ROLE enforced internally oz uses maps so 0 address will return true but does not break anything
function removeMinter(address minterAddress) external { revokeRole(MINTER, minterAddress); }
9,711,503
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view {
1,019,031
pragma solidity ^0.4.20; // Solidity compiler version supported by Azure Blockchain Workbench //--------------------------------------------- //Generated automatically for application 'BasicProvenance' by AppCodeGen utility //--------------------------------------------- import "./BasicProvenance.sol"; contract WorkbenchBase { event WorkbenchContractCreated(string applicationName, string workflowName, address originatingAddress); event WorkbenchContractUpdated(string applicationName, string workflowName, string action, address originatingAddress); string internal ApplicationName; string internal WorkflowName; function WorkbenchBase(string applicationName, string workflowName) public { ApplicationName = applicationName; WorkflowName = workflowName; } function ContractCreated() public { WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender); } function ContractUpdated(string action) public { WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender); } } // // The wrapper contract BasicProvenance_AzureBlockchainWorkBench invokes functions from BasicProvenance. // The inheritance order of BasicProvenance_AzureBlockchainWorkBench ensures that functions and variables in BasicProvenance // are not shadowed by WorkbenchBase. // Any access of WorkbenchBase function or variables is qualified with WorkbenchBase // contract BasicProvenance_AzureBlockchainWorkBench is WorkbenchBase, BasicProvenance { // // Constructor // function BasicProvenance_AzureBlockchainWorkBench(address supplyChainOwner, address supplyChainObserver) WorkbenchBase("BasicProvenance", "BasicProvenance") BasicProvenance(supplyChainOwner, supplyChainObserver) public { // Check postconditions and access control for constructor of BasicProvenance // Constructor should transition the state to StartState assert(State == StateType.Created); // Signals successful creation of contract BasicProvenance WorkbenchBase.ContractCreated(); } //////////////////////////////////////////// // Workbench Transitions // // Naming convention of transition functions: // Transition_<CurrentState>_Number_<TransitionNumberFromCurrentState>_<FunctionNameOnTransition> // Transition function arguments same as underlying function // ////////////////////////////////////////////// function Transition_Created_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.Created); require(msg.sender == InitiatingCounterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_InTransit_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Counterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_InTransit_Number_1_Complete () public { // Transition preconditions require(State == StateType.InTransit); // Call overridden function Complete in this contract Complete(); // Transition postconditions assert(State == StateType.Completed); } function TransferResponsibility(address newCounterparty) public { // Placeholder for function preconditions // Call function TransferResponsibility of BasicProvenance BasicProvenance.TransferResponsibility(newCounterparty); // Placeholder for function postconditions // Signals successful execution of function TransferResponsibility WorkbenchBase.ContractUpdated("TransferResponsibility"); } function Complete() public { // Placeholder for function preconditions // Call function Complete of BasicProvenance BasicProvenance.Complete(); // Placeholder for function postconditions // Signals successful execution of function Complete WorkbenchBase.ContractUpdated("Complete"); } }
Transition preconditions Call overridden function Complete in this contract Transition postconditions
function Transition_InTransit_Number_1_Complete () public { require(State == StateType.InTransit); Complete(); assert(State == StateType.Completed); }
6,375,321
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IVotingPowerFormula.sol"; import "./lib/ReentrancyGuardUpgradeable.sol"; import "./lib/PrismProxyImplementation.sol"; import "./lib/VotingPowerStorage.sol"; import "./lib/SafeERC20.sol"; /** * @title VotingPower * @dev Implementation contract for voting power prism proxy * Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract * The exception to this is the `become` function specified in PrismProxyImplementation * This function is called once and is used by this contract to accept its role as the implementation for the prism proxy */ contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; /// @notice restrict functions to just owner address modifier onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); require(msg.sender == app.owner, "only owner"); _; } /// @notice An event that's emitted when a user's staked balance increases event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when a user's staked balance decreases event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when an account's vote balance changes event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance); /// @notice Event emitted when the owner of the voting power contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /** * @notice Initialize VotingPower contract * @dev Should be called via VotingPowerPrism before calling anything else * @param _edenToken address of EDEN token */ function initialize( address _edenToken, address _owner ) public initializer { __ReentrancyGuard_init_unchained(); AppStorage storage app = VotingPowerStorage.appStorage(); app.edenToken = IEdenToken(_edenToken); app.owner = _owner; } /** * @notice Address of EDEN token * @return Address of EDEN token */ function edenToken() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return address(app.edenToken); } /** * @notice Decimals used for voting power * @return decimals */ function decimals() public pure returns (uint8) { return 18; } /** * @notice Address of token registry * @return Address of token registry */ function tokenRegistry() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return address(app.tokenRegistry); } /** * @notice Address of lockManager * @return Address of lockManager */ function lockManager() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return app.lockManager; } /** * @notice Address of owner * @return Address of owner */ function owner() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return app.owner; } /** * @notice Sets token registry address * @param registry Address of token registry */ function setTokenRegistry(address registry) public onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); app.tokenRegistry = ITokenRegistry(registry); } /** * @notice Sets lockManager address * @param newLockManager Address of lockManager */ function setLockManager(address newLockManager) public onlyOwner { AppStorage storage app = VotingPowerStorage.appStorage(); app.lockManager = newLockManager; } /** * @notice Change owner of vesting contract * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "VP::changeOwner: not valid address"); AppStorage storage app = VotingPowerStorage.appStorage(); emit ChangedOwner(app.owner, newOwner); app.owner = newOwner; } /** * @notice Stake EDEN tokens using offchain approvals to unlock voting power * @param amount The amount to stake * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant { require(amount > 0, "VP::stakeWithPermit: cannot stake 0"); AppStorage storage app = VotingPowerStorage.appStorage(); require(app.edenToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens"); app.edenToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _stake(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Stake EDEN tokens to unlock voting power for `msg.sender` * @param amount The amount to stake */ function stake(uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::stake: cannot stake 0"); require(app.edenToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens"); require(app.edenToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking"); _stake(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Stake LP tokens to unlock voting power for `msg.sender` * @param token The token to stake * @param amount The amount to stake */ function stake(address token, uint256 amount) external nonReentrant { IERC20 lptoken = IERC20(token); require(amount > 0, "VP::stake: cannot stake 0"); require(lptoken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens"); require(lptoken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking"); AppStorage storage app = VotingPowerStorage.appStorage(); address tokenFormulaAddress = app.tokenRegistry.tokenFormulas(token); require(tokenFormulaAddress != address(0), "VP::stake: token not supported"); IVotingPowerFormula tokenFormula = IVotingPowerFormula(tokenFormulaAddress); uint256 votingPower = tokenFormula.convertTokensToVotingPower(amount); _stake(msg.sender, token, amount, votingPower); } /** * @notice Count locked tokens toward voting power for `account` * @param account The recipient of voting power * @param amount The amount of voting power to add */ function addVotingPowerForLockedTokens(address account, uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::addVPforLT: cannot add 0 voting power"); require(msg.sender == app.lockManager, "VP::addVPforLT: only lockManager contract"); _increaseVotingPower(account, amount); } /** * @notice Remove unlocked tokens from voting power for `account` * @param account The account with voting power * @param amount The amount of voting power to remove */ function removeVotingPowerForUnlockedTokens(address account, uint256 amount) external nonReentrant { AppStorage storage app = VotingPowerStorage.appStorage(); require(amount > 0, "VP::removeVPforUT: cannot remove 0 voting power"); require(msg.sender == app.lockManager, "VP::removeVPforUT: only lockManager contract"); _decreaseVotingPower(account, amount); } /** * @notice Withdraw staked EDEN tokens, removing voting power for `msg.sender` * @param amount The amount to withdraw */ function withdraw(uint256 amount) external nonReentrant { require(amount > 0, "VP::withdraw: cannot withdraw 0"); AppStorage storage app = VotingPowerStorage.appStorage(); _withdraw(msg.sender, address(app.edenToken), amount, amount); } /** * @notice Withdraw staked LP tokens, removing voting power for `msg.sender` * @param token The token to withdraw * @param amount The amount to withdraw */ function withdraw(address token, uint256 amount) external nonReentrant { require(amount > 0, "VP::withdraw: cannot withdraw 0"); Stake memory s = getStake(msg.sender, token); uint256 vpToWithdraw = amount * s.votingPower / s.amount; _withdraw(msg.sender, token, amount, vpToWithdraw); } /** * @notice Get total amount of EDEN tokens staked in contract by `staker` * @param staker The user with staked EDEN * @return total EDEN amount staked */ function getEDENAmountStaked(address staker) public view returns (uint256) { return getEDENStake(staker).amount; } /** * @notice Get total amount of tokens staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total amount staked */ function getAmountStaked(address staker, address stakedToken) public view returns (uint256) { return getStake(staker, stakedToken).amount; } /** * @notice Get staked amount and voting power from EDEN tokens staked in contract by `staker` * @param staker The user with staked EDEN * @return total EDEN staked */ function getEDENStake(address staker) public view returns (Stake memory) { AppStorage storage app = VotingPowerStorage.appStorage(); return getStake(staker, address(app.edenToken)); } /** * @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total staked */ function getStake(address staker, address stakedToken) public view returns (Stake memory) { StakeStorage storage ss = VotingPowerStorage.stakeStorage(); return ss.stakes[staker][stakedToken]; } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function balanceOf(address account) public view returns (uint256) { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 nCheckpoints = cs.numCheckpoints[account]; return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "VP::balanceOfAt: not yet determined"); CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 nCheckpoints = cs.numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return cs.checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (cs.checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = cs.checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return cs.checkpoints[account][lower].votes; } /** * @notice Internal implementation of stake * @param voter The user that is staking tokens * @param token The token to stake * @param tokenAmount The amount of token to stake * @param votingPower The amount of voting power stake translates into */ function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal { IERC20(token).safeTransferFrom(voter, address(this), tokenAmount); StakeStorage storage ss = VotingPowerStorage.stakeStorage(); ss.stakes[voter][token].amount = ss.stakes[voter][token].amount + tokenAmount; ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower + votingPower; emit Staked(voter, token, tokenAmount, votingPower); _increaseVotingPower(voter, votingPower); } /** * @notice Internal implementation of withdraw * @param voter The user with tokens staked * @param token The token that is staked * @param tokenAmount The amount of token to withdraw * @param votingPower The amount of voting power stake translates into */ function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal { StakeStorage storage ss = VotingPowerStorage.stakeStorage(); require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked"); require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power"); ss.stakes[voter][token].amount = ss.stakes[voter][token].amount - tokenAmount; ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower - votingPower; IERC20(token).safeTransfer(voter, tokenAmount); emit Withdrawn(voter, token, tokenAmount, votingPower); _decreaseVotingPower(voter, votingPower); } /** * @notice Increase voting power of voter * @param voter The voter whose voting power is increasing * @param amount The amount of voting power to increase by */ function _increaseVotingPower(address voter, uint256 amount) internal { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 checkpointNum = cs.numCheckpoints[voter]; uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0; uint256 votingPowerNew = votingPowerOld + amount; _writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew); } /** * @notice Decrease voting power of voter * @param voter The voter whose voting power is decreasing * @param amount The amount of voting power to decrease by */ function _decreaseVotingPower(address voter, uint256 amount) internal { CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); uint32 checkpointNum = cs.numCheckpoints[voter]; uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0; uint256 votingPowerNew = votingPowerOld - amount; _writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew); } /** * @notice Create checkpoint of voting power for voter at current block number * @param voter The voter whose voting power is changing * @param nCheckpoints The current checkpoint number for voter * @param oldVotes The previous voting power of this voter * @param newVotes The new voting power of this voter */ function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits"); CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage(); if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); cs.numCheckpoints[voter] = nCheckpoints + 1; } emit VotingPowerChanged(voter, oldVotes, newVotes); } /** * @notice Converts uint256 to uint32 safely * @param n Number * @param errorMessage Error message to use if number cannot be converted * @return uint32 number */ function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } }
Address of lockManager return Address of lockManager/
function lockManager() public view returns (address) { AppStorage storage app = VotingPowerStorage.appStorage(); return app.lockManager; }
7,225,145
./full_match/1/0x5F0752b1Da55277f7FaF478Bc30857B25FE10edD/sources/localhost/picontract/picontract.sol
_pi ๆ˜ฏๆŒ‡ pi token ็š„ๅˆ็บฆ _entrance ๆŒ‡ pi token ็š„้“ธๅธๅˆ็บฆ _balancer ๆ˜ฏ pi token/weth ๅˆ็บฆ็š„ๅœฐๅ€ _minAmountOut ๆ˜ฏๆœ€ๅŽๆœ€ๅฐ‘้œ€่ฆ่Žทๅพ—ๅคšๅฐ‘ weth buy token at balancer exit the pie pool check result
function balancerToPi( address _entrance, address _balancer, uint256 _slippageDiscount, uint256 _slippageDiscountBase ) public payable onlyTrader { uint256 ethIn = (msg.value % (1 ether)) * 100; uint256 maxPrice = 1000000000000000000000000000; uint256 _minAmountOut = ethIn * _slippageDiscount / _slippageDiscountBase; IEntrance entrance = IEntrance(_entrance); address _pi = entrance.pipt(); IPi pi = IPi(_pi); IBalancer balancer = IBalancer(_balancer); uint256 piAmountOut = balancer.calcOutGivenIn( balancer.getBalance(weth), balancer.getNormalizedWeight(weth), balancer.getBalance(_pi), balancer.getNormalizedWeight(_pi), ethIn, balancer.getSwapFee() ); (, , uint256 ethAmountOut, ) = entrance.calcSwapPiptToEthInputs(piAmountOut, pi.getFinalTokens()); require(ethAmountOut >= _minAmountOut, "limit out"); balancer.swapExactAmountOut(weth, ethIn, _pi, piAmountOut, maxPrice); uint256 piAmount = pi.balanceOf(address(this)); entrance.swapPiptToEth(piAmount); wethContract.withdraw(wethContract.balanceOf(address(this))); require(address(this).balance >= ethIn, "ethOut must > ethIn"); msg.sender.transfer(msg.value); }
8,426,677
pragma solidity ^0.4.20; /* โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–ˆโ–ˆโ”€ โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */ contract POW33 { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "POW33"; string public symbol = "PW33"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 3; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function POW33() public { // add administrators here administrators[0x3446e0F8Bc2556a2f00A317D89549DBbD6e26458] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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; } }
-- APPLICATION ENTRY POINTS --/ add administrators here
function POW33() public { administrators[0x3446e0F8Bc2556a2f00A317D89549DBbD6e26458] = true; }
10,123,304